Nodejs Cors 发布 Nodejs 和 React(生产)
Nodejs Cors issue Nodejs and React (production)
我在从浏览器获取请求时遇到问题,这很烦人!
任何提示都非常感谢。
提前致谢!
我的 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 Error I am getting
你可以在你的 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"
告诉服务器只允许这些 header。如果您查看您的请求,您会发现 header.
"Access-Control-Allow-Origin": "*"
这将在提出请求时包含在 header 中。这被服务器拒绝了。
试试这个
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);
};
此致,
周杰伦
我在从浏览器获取请求时遇到问题,这很烦人! 任何提示都非常感谢。 提前致谢!
我的 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 Error I am getting
你可以在你的 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"
告诉服务器只允许这些 header。如果您查看您的请求,您会发现 header.
"Access-Control-Allow-Origin": "*"
这将在提出请求时包含在 header 中。这被服务器拒绝了。
试试这个
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);
};
此致, 周杰伦