本文介绍了XMLHttpRequest无法加载否请求的资源上存在“Access-Control-Allow-Origin”标头。 Origin'http:// localhost:3000'谷歌地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我的节点js代码

  import express from '表现'; 
从'path'导入路径;
从'body-parser'中导入bodyParser;

//导入至Pord
从'./routes/api'导入api;
从'./routes/auth'导入auth
从'cookie-parser'导入cookieParser;
从'./middleware/authCheck'导入{LoginCheck};
从'cors'进口cors;


//所有Webpack资料
从'../../webpack.config.dev'导入webpackConfig;
从'webpack'导入webpack;
从'webpack-dev-middleware'导入webpackMiddleware
从'webpack-hot-middleware'导入webpackHotMidleware;


//服务器端渲染材料
从'react-router'导入{match,RouterContext};
从'react-redux'导入{Provider};
从'redux'导入{dispatch};
从'react-dom / server'导入{renderToString,renderToStaticMarkup};
从'../../src/client/Reducers'导入缩减器;
从'../client/routes'导入路由;
从'redux-thunk'导入thunk;
从'redux'导入{createStore,applyMiddleware}
导入从'react'反应
从'react-helmet'导入头盔;
从'serialize-javascript'导入serialize;


// PassPort Stuff Import This



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


const编译器= webpack(webpackConfig);
$ b $ app.use(webpackMiddleware(编译器,{
hot:true,
publicPath:webpackConfig.output.publicPath,
noInfo:true
}) );

app.use(webpackHotMidleware(compiler));



app.use(cors());
app.use(cookieParser('sdkhcvlsd684684JJJklvblsdkuvgblsduvblsidvksdjbvlsjvuywlsfvliusdgv'));
//检查认证MiddleWare
app.use(LoginCheck)
// Passport Api
app.use('/ auth',auth);
//我们的Api
app.use('/ p',api);


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

// res.sendFile( path.join(__ dirname,'../../index.html'))
//服务器端渲染开始
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 = {}
$ b $ const store = createStore (reducer,initialState,applyMiddleware(thunk));


const {loc ation,params,history} = renderProps

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


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


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>窗口.__ STATE __ = $ {JSON.stringify(state)}< / script>

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



})
});


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

这是我的axios请求

 导出函数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网络服务。因此,由于浏览器的同源策略,您将无法从客户端JavaScript代码调用Places API Web服务。



为了使用Places在客户端JavaScript中,您必须使用Google Maps JavaScript API的Places库。地点图书馆有附近的雷达和文本搜索功能,非常类似于相应的网络服务。



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





希望它有帮助!

I am new to React js I am trying to simple dynamically changing map with respected to user input But for specific place seach request this error rises

this is my node js code

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')
});

this is my axios request

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
        })
    }

}
解决方案

The CORS headers are not set for Places API web service on Google backend servers. So you won't be able to call Places API web service from the client side JavaScript code due to the Same-Origin policy of the browsers.

In order to use Places on client side JavaScript you have to use a Places library of Google Maps JavaScript API. The places library has nearby, radar and text search functionality very similar to the corresponding web service.

For further details please have a look at the documentation:

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

Hope it helps!

这篇关于XMLHttpRequest无法加载否请求的资源上存在“Access-Control-Allow-Origin”标头。 Origin'http:// localhost:3000'谷歌地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 01:25