admin管理员组文章数量:1302342
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
XMLHttpRequest cannot load …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.
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 piler = webpack(webpackConfig);
app.use(webpackMiddleware(piler, {
hot: true,
publicPath: webpackConfig.output.publicPath,
noInfo: true
}));
app.use(webpackHotMidleware(piler));
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 ponents = renderPropsponents;
const Comp = ponents[ponents.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) {
// .0826802,80.2707184&radius=500&keyword=parks&key=AIzaSyAZbur2hq7p3UxjYrA2_G4ctpswFi0pO3A
console.log(coords)
return dispatch => {
return axios.get(`=${coords.lat},${coords.lng}&radius=1000&keyword=${term}&key=${config.MAP_API}`).then(response => {
return response.data
})
}
}
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
XMLHttpRequest cannot load https://maps.googleapis./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.
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 piler = webpack(webpackConfig);
app.use(webpackMiddleware(piler, {
hot: true,
publicPath: webpackConfig.output.publicPath,
noInfo: true
}));
app.use(webpackHotMidleware(piler));
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 ponents = renderProps.ponents;
const Comp = ponents[ponents.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./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./maps/api/place/nearbysearch/json?location=${coords.lat},${coords.lng}&radius=1000&keyword=${term}&key=${config.MAP_API}`).then(response => {
return response.data
})
}
}
Share
Improve this question
edited Jun 27, 2018 at 8:11
xomena
32.2k6 gold badges96 silver badges125 bronze badges
asked Apr 8, 2017 at 12:45
NaneNane
4336 gold badges39 silver badges82 bronze badges
6
- 1 Ask the backend guy to implement CORS. Nothing to do with react. – Ved Commented Apr 8, 2017 at 12:51
- I used this middle ware app.use(cors()); But no use – Nane Commented Apr 8, 2017 at 12:58
- 3 You need to check that properly. But it is all backend stuff. No Reactjs issue. – Ved Commented Apr 8, 2017 at 12:59
- Possibly already answered here. stackoverflow./questions/28359730/… – Todd Chaffee Commented Apr 8, 2017 at 13:00
- Possibly axios doesn't support jsonp @ToddChaffee – Nane Commented Apr 8, 2017 at 13:08
1 Answer
Reset to default 9The 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./maps/documentation/javascript/places
Hope it helps!
本文标签:
版权声明:本文标题:javascript - XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on the requested reso 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741706337a2393582.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论