1

webpack-dev-middleware在我的 React 应用程序中使用。当我在 中提供谷歌地图资产时index.html,它工作得很好,但是,我想使用 React 组件中获取这些资产axios,当我这样做时,我收到以下错误:

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

1 回答 1

1

所以我找到了几种解决方案的成功:

1) 我动态创建了一个指向 google maps 目标的脚本文件并将其注入到 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

于 2016-06-27T19:30:21.217 回答