首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >XMLHttpRequest无法在请求的资源上加载“访问-控制-允许-原产地”标头。Http://localhost:3000‘谷歌地图

XMLHttpRequest无法在请求的资源上加载“访问-控制-允许-原产地”标头。Http://localhost:3000‘谷歌地图
EN

Stack Overflow用户
提问于 2017-04-08 12:45:24
回答 1查看 6.9K关注 0票数 3

我是新的反应js,我试图简单动态地改变地图与尊重的用户输入,但对于特定的地方seach请求,这个错误上升。

XMLHttpRequest无法加载https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=undef…ined&radius=1000&keyword=fdtbf&key=myapikey。请求的资源上没有“访问-控制-允许-原产地”标题。因此,“http://localhost:3000”源是不允许访问的。

这是我的节点js代码

代码语言:javascript
运行
复制
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请求

代码语言:javascript
运行
复制
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
        })
    }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-08 17:09:43

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

为了使用客户端JavaScript上的位置,您必须使用Google API的Places。地点库的附近、雷达和文本搜索功能非常类似于相应的web服务。

欲知更多详情,请参阅下列文件:

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

希望能帮上忙!

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43294257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档