[英]React+Express: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
I am running a node/express server that is currently my backend and is hosting the API.我正在运行一个 node/express 服务器,它当前是我的后端并托管 API。 I can access the API on port 123 with postman just fine.我可以通过邮递员访问端口 123 上的 API。 I am creating my frontend in React and trying to access the API to get some data.我正在 React 中创建我的前端并尝试访问 API 以获取一些数据。 However, when I try to navigate to the page I get the following error in the console.但是,当我尝试导航到该页面时,控制台中出现以下错误。
Access to XMLHttpRequest at 'http://abc:123/test' from origin 'http://abc:456' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
createError.js:17 Uncaught (in promise) Error: Network Error
at createError (createError.js:17)
at XMLHttpRequest.handleError (xhr.js:80)
I have added the following to my server however still receiving the error, any suggestion on what I could be missing?我已将以下内容添加到我的服务器,但仍然收到错误,关于我可能遗漏的任何建议?
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
next();
})
In my React code I am using axios to make a post request to the API在我的 React 代码中,我使用 axios 向 API 发出发布请求
axios.post("http://abc:123/test", {
'data': '12346'
}).then(response => {
console.log(response);
})
I don't really know, but it seems like you can add proxy": " http://abc:123 " to your package.json file我真的不知道,但您似乎可以将 proxy":" http://abc:123 " 添加到您的 package.json 文件中
Example:例子:
"proxy": "http://abc:123",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
And then:进而:
axios.post("/test", {
'data': '12346'
}).then(response => {
console.log(response);
})
does fetch works? fetch 有效吗? Can you try with fetch?你可以试试 fetch 吗?
The pre flight request is an OPTIONS request, you only answer POST requests.飞行前请求是一个 OPTIONS 请求,您只回答 POST 请求。 Add添加
app.post(/*...*/);
app.options("http://abc:123/test", (req, res) =>
res.status(200).send("Feel free to send the real request now :)")
);
Or add something like the npm cors package, that does that for you too.或者添加类似 npm cors 包的东西,它也适合你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.