【发布时间】:2021-10-17 04:48:51
【问题描述】:
我有一个使用 Express server 进行服务器端渲染的反应应用程序。我想使用 axios 发出 POST 请求,但它被 CORS 错误阻止: “从源 'http://localhost:4249' 访问 XMLHttpRequest 在 'https://xyz/abc' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否 'Access-Control-请求的资源上存在 Allow-Origin' 标头。
我在我的服务器调用中添加了允许源头和 cors 模块后尝试过,但没有成功
import cors from "cors";
const server = express();
server.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Methods",
"OPTIONS, GET, POST, PUT, PATCH, DELETE"
);
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
server.use(express.static("dist"));
server.use(cors());
这是 axios 请求:
const headers = {
Accept: "application/json",
"x-ms-version": "2019-07-11",
Authorization: token,
"x-ms-date": date,
"x-ms-documentdb-isquery": true,
"Content-Type": "application/query+json",
"x-ms-documentdb-query-enablecrosspartition": "true",
"cache-control": "no-cache",
"Access-Control-Allow-Origin": "*",
};
useEffect(() => {
axios
.post(
"https://xyz/abc",
data,
{
headers: headers,
}
)
.then(function (response) {
setres(response.data);
})
.catch(function (error) {
console.log(error);
});
}, []);
Webpack 配置:
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.(sass|css|scss)$/,
use: ["style-loader", "css-loader"],
},
],
},
};
【问题讨论】:
-
你为什么要与
HTTPlocalhost 通信HTTPS:xyz?