gpt4 book ai didi

javascript - XMLHttpRequest 无法加载请求的资源上不存在 'Access-Control-Allow-Origin' header 。起源 'http://localhost:3000' 谷歌地图

转载 作者:搜寻专家 更新时间:2023-10-31 23:32:25 26 4
gpt4 key购买 nike

我是 React js 的新手,我正在尝试根据用户输入简单地动态更改 map 但是对于特定位置的搜索请求,此错误会增加

XMLHttpRequest cannot load https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=undef…ined&radius=1000&keyword=fdtbf&key=myapikey. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

这是我的 Node js代码

import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';

//Import To Pord
import api from './routes/api';
import auth from './routes/auth'
import cookieParser from 'cookie-parser';
import {LoginCheck} from './middleware/authCheck';
import cors from 'cors';


//All Webpack Stuff
import webpackConfig from '../../webpack.config.dev';
import webpack from 'webpack';
import webpackMiddleware from 'webpack-dev-middleware'
import webpackHotMidleware from 'webpack-hot-middleware';


//Server Side Rendering Stuff
import {match, RouterContext } from 'react-router';
import { Provider } from 'react-redux';
import { dispatch } from 'redux';
import { renderToString, renderToStaticMarkup } from 'react-dom/server';
import reducer from '../../src/client/Reducers';
import routes from '../client/routes';
import thunk from 'redux-thunk';
import { createStore ,applyMiddleware} from 'redux'
import React from 'react'
import Helmet from 'react-helmet';
import serialize from 'serialize-javascript';


//PassPort Stuff Import This




let app = express();
app.use(bodyParser.json());
app.use(express.static('public'))


const compiler = webpack(webpackConfig);

app.use(webpackMiddleware(compiler, {
hot: true,
publicPath: webpackConfig.output.publicPath,
noInfo: true
}));

app.use(webpackHotMidleware(compiler));



app.use(cors());
app.use(cookieParser('sdkhcvlsd684684JJJklvblsdkuvgblsduvblsidvksdjbvlsjvuywlsfvliusdgv'));
//Check Auth MiddleWare
app.use(LoginCheck)
//Passport Api
app.use('/auth',auth);
//Our Api
app.use('/p',api);



app.get('/*', (req, res,next) => {

// res.sendFile(path.join(__dirname, '../../index.html'))
// Server Side Rendering Starts
match({routes:routes(),location:req.url},(err,redirectLocation,renderProps) => {
if (err) return next(err);


if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search)
}

// if (!renderProps) {
// res.redirect('/404')
// }

const components = renderProps.components;

const Comp = components[components.length - 1].WrappedComponent;

const fetchData = (Comp && Comp.fetchData) || (() => Promise.resolve())

const initialState = {}

const store = createStore(reducer, initialState, applyMiddleware(thunk));


const { location, params, history } = renderProps

fetchData({ store, location, params, history }).then(() => {
const body = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
)

const state = store.getState();
// console.log(state)


let head = Helmet.rewind();
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.send(`<!DOCTYPE html>
<html>
<head>
${head.title}
${head.meta}
${head.link}
</head>
<body>
<div id="app" >${body}</div>
<script>window.__STATE__=${JSON.stringify(state)}</script>

<script src="/bundle.js"></script>
</body>
</html>`)
})
.catch((err) => next(err))



})
});


app.listen(3000 ,() => {
console.log('Listening')
});

这是我的 axios 请求

export function getPlaceFromCoords(term,coords) {
// https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=13.0826802,80.2707184&radius=500&keyword=parks&key=AIzaSyAZbur2hq7p3UxjYrA2_G4ctpswFi0pO3A
console.log(coords)
return dispatch => {
return axios.get(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${coords.lat},${coords.lng}&radius=1000&keyword=${term}&key=${config.MAP_API}`).then(response => {
return response.data
})
}

}

最佳答案

没有为 Google 后端服务器上的 Places API 网络服务设置 CORS header 。因此,由于浏览器的同源策略,您将无法从客户端 JavaScript 代码调用 Places API 网络服务。

要在客户端 JavaScript 上使用 Places,您必须使用 Google Maps JavaScript API 的 Places 库。地点库具有与相应网络服务非常相似的附近、雷达和文本搜索功能。

有关详细信息,请查看文档:

https://developers.google.com/maps/documentation/javascript/places

希望对您有所帮助!

关于javascript - XMLHttpRequest 无法加载请求的资源上不存在 'Access-Control-Allow-Origin' header 。起源 'http://localhost:3000' 谷歌地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43294257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com