我一直在尝试从本地开发服务器(web-pack 开发服务器)上的浏览器中运行的React应用程序进行API调用(在本地主机上运行express的nodejs)。一切都运行良好,直到我尝试调用 api。它们都在不同的端口上运行。
我尝试将 cors header (MDN 推荐)添加到 post 调用(来自浏览器中的应用程序)和 Nodejs API 的响应,但这些都没有解决问题。
API 调用代码(在浏览器中):
const headers = {
'Content-Type': 'application/json',
'access-token': '',
'Access-Control-Allow-Origin': '*',
}
export default async () => {
try {
const body = JSON.stringify({
test: true,
})
const response = await fetch('http://localhost:1337/internal/provider/check_email_exist', {
method: 'POST',
headers,
body,
})
console.log(response)
} catch (e) {
return e
}
}
API中间件(在nodejs中):
// Verify All Requests
app.use(VerifyToken)
// Compress
app.use(compression())
// Helmet middlware
app.use(helmet())
// Body Parser
app.use(bodyParser.urlencoded({
extended: false,
}))
app.use(bodyParser.json())
预期结果是仅给出 200 状态代码并响应数据。
实际输出是:
OPTIONS http://localhost:1337/internal/provider/check_email_exist 404 (Not Found)
Access to fetch at 'http://localhost:1337/internal/provider/check_email_exist' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
最佳答案
由于您使用的是webpack-dev-server
,您可以使用proxy
选项 DevServerProxy .
您的配置将如下所示:
// webpack.config.js
devServer: {
proxy: {
'/internal': 'http://localhost:1337'
}
}
由于我在您的问题上看不到您的 express
路由,因此我推测如果您的 API
位于 /internal
上,则使用代理路由> 端点那么你应该像这样修改你的 React 代码:
const response = await fetch('/internal/provider/check_email_exist', {
method: 'POST',
headers,
body,
})
如您所见,我省略了 https://localhost:1337
因为 webpack-dev-server
中的 proxy
选项将处理它将重定向到http://localhost:1337
。希望对你有帮助。干杯,西格弗里德。
编辑
正如对您问题的评论所指出的,您应该在 express
服务器上设置 header ,而不是在客户端上,对于此任务,您可以使用 cors-middleware包。
关于node.js - 如何修复 "Response to preflight request doesn' t 通过访问控制检查 : It does not have HTTP ok status"error in react app with nodejs api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56083049/