【问题标题】:CORS with React, Webpack and AxiosCORS 与 React、Webpack 和 Axios
【发布时间】:2018-04-04 06:45:48
【问题描述】:

如何使用 webpack 和 axios 在 react 前端应用中设置 CORS Header。

我想从 API 网址获得响应。我是否必须使用 express 设置单独的服务器,或者可以使用前端应用程序中的 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.

【问题讨论】:

标签: javascript reactjs webpack cors axios


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-02-12
      • 2021-01-26
      • 2021-10-17
      • 2016-12-15
      • 2018-06-06
      • 2022-06-30
      • 2021-05-30
      • 2021-04-19
      • 2020-06-10
      相关资源
      最近更新 更多