与React,Webpack和Axios的CORS

时间:2017-10-23 16:23:38

标签: reactjs webpack cors axios

如何使用webpack和axios在反应前端应用程序中设置CORS标头。

我想从API网址获得回复。我是否必须使用let表示快速设置sepparate服务器,或者可以使用前端应用程序中的webpack-dev-server来完成。

我收到错误:

Failed to load https://api.test.io/test/res: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

2 个答案:

答案 0 :(得分:2)

问题在于服务器,而不是Axios。您需要设置webpack devServer标头以允许CORS。

devServer: {
   headers: { 
       "Access-Control-Allow-Origin": "*",
       "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
   }
}

答案 1 :(得分:0)

您没有设置 CORS 标头客户端,它们是由浏览器自动发送的。你做服务器端。配置Webpack服务器以回复Access-Control-Allow-Origin设置为通配符*

devServer: {
   headers: { 
       "Access-Control-Allow-Origin": "*"
   }
}