我在我的React应用程序中使用webpack-dev-middleware。当我在index.html中提供google资产时,它工作得很好,但是,我想使用axios在一个React组件中获取这些资产,当我这样做时,我会得到以下错误:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.我尝试在webpack-dev-middleware中设置这些设置,但仍然遇到相同的问题:
webpackDevMiddleware(bundler, {
...
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Headers': 'X-Requested-With,content-type',
'Access-Control-Allow-Credentials': true
}
}),发布于 2016-06-27 19:30:21
因此,我发现了几种解决方案的成功:
1)我动态地创建了一个指向google映射目标的脚本文件,并将其注入DOM
`const script = document.createElement('script'); script.setAttribute('src', 'https://maps.googleapis.com/maps/api/js?key=.....'); document.body.appendChild(script);` 2)在意识到我基本上是在重建JSONP正在做的事情之后,我选择了使用JSONP方法,您可以使用jquery axios方法,也可以使用像jsonp这样的模块。
https://stackoverflow.com/questions/38059938
复制相似问题