gpt4 book ai didi

reactjs - 使用 create-react-app 和 webpack 发出 CORS API 请求 - 无 express

转载 作者:行者123 更新时间:2023-12-03 13:42:49 27 4
gpt4 key购买 nike

我正在尝试在不禁用浏览器中 CORS 的情况下进行 API 调用。该应用程序是使用react-create-app 创建的。它使用 webpack 和 webpackDevServer 进行开发。我在这里找到的所有答案都说将以下代码放入我的 webpack.config 文件中。

devServer: {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
}
}

但是,我已经在许多不同的地方尝试过,但它不起作用。

我继续收到错误:

Failed to load resource: the server responded with a status of 500 ()

Failed to load ... 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. The response had HTTP status code 500.

我还尝试将我的调用从 axios 调用更改为 fetch 调用

return fetch(process.env.REACT_APP_API_URL + "/prod/user", {
mode: 'no-cors',
credentials: 'include',
method: "GET",
headers: {
"x-api-key": process.env.REACT_APP_API_KEY
}
})
.then(response => {
return response.json()
})
.then(resp => dispatch(receiveUsers(resp.data)))
.catch(error => {console.log(error)})

这让我更接近了,但控制台现在正在返回

响应 {type: "opaque", url: "", redirected: false, status: 0, ok: false, ...}

如何解决 CORS 问题?预先感谢您的帮助!

Response/Request Headers

最佳答案

尚无法添加评论,所以我会将其作为答案。

如果您尝试访问由另一个节点应用程序或另一个主机提供的 API。您可以配置 webpack-dev-server 将该请求代理到真实服务器。

检查Create React App Doc: Proxying API Requests in Development了解更多详情。

关于reactjs - 使用 create-react-app 和 webpack 发出 CORS API 请求 - 无 express ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50008667/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com