[英]Nodejs Cors issue Nodejs and React (production)
I have an issue getting requests from the browser and it is getting annoying.我在从浏览器获取请求时遇到问题,并且越来越烦人。 Any hints are highly appreciated.
任何提示都非常感谢。 Thanks in advance!
提前致谢!
I have nodejs setup as follows:我的nodejs设置如下:
const express = require("express");
const cors = require("cors");
const app = express();
app.use(
cors({
origin: "*",
methods: "GET,POST",
allowedHeaders: "Content-Type,Authorization",
credentials: true,
preflightContinue: true,
})
);
app.use(express.json());
....
in Reacr Axios requests as follow在 Reacr Axios 请求如下
const getComments = () => {
const config = {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
method: "GET",
url: `${url}/all`,
withCredentials: true,
crossorigin: true,
"Access-Control-Allow-Origin": "*",
};
return axios(config)
.then(serviceHelper.onGlobalSuccess)
.catch(serviceHelper.onGlobalError);
};
You can try this in your nodejs code你可以在你的nodejs代码中试试这个
const express = require('express');
let server = express();
server.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With,Content-Type,Accept'
);
next();
});
This line这条线
allowedHeaders: "Content-Type, Authorization"
tells the server to allow only these headers.告诉服务器只允许这些标头。 If you look into your request, you have this header.
如果您查看您的请求,您将获得此 header。
"Access-Control-Allow-Origin": "*"
This will be included in the header while making a request.这将在发出请求时包含在 header 中。 This is getting rejected by the server.
这被服务器拒绝了。
Instead of that, try this而不是那个,试试这个
const getComments = () => {
const config = {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
method: "GET",
url: `${url}/all`,
withCredentials: true,
};
return axios(config)
.then(serviceHelper.onGlobalSuccess)
.catch(serviceHelper.onGlobalError);
};
regards, Jay问候,杰伊
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.