我在从浏览器获取请求时遇到问题,这越来越烦人!如有任何提示,我们将不胜感激。提前感谢!
我有如下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());
....
在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);
};
Cors错误我正在获取
您可以在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();
});
此行
allowedHeaders: "Content-Type, Authorization"
告诉服务器只允许这些头。如果你仔细查看你的请求,你就会得到这个标题。
"Access-Control-Allow-Origin": "*"
这将在发出请求时包含在标头中。这将被服务器拒绝。
相反,试试这个
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);
};
问候,Jay