【发布时间】:2020-05-25 13:31:21
【问题描述】:
我正在使用 react & express 作为一个简单的表单 当我将我的反应表单发布到快递服务器时,我得到了这个
Access to XMLHttpRequest at 'http://localhost:4000/api/user' from origin 'http://localhost:9000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
这就是我在我的 express server.js 中尝试过的:
const cors = require("cors");
app.use(
cors({
origin: "*",
credentials: true
})
);
在我的中间人
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "localhost:9000");
res.header("Access-Control-Allow-Credentials", true);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
});
我尝试通过 axios 发布请求:
axios
.post("http://localhost:4000/api/user", data)
.then(() => console.log("Tadaaa"))
.catch(err => {
console.error(err);
});
【问题讨论】:
-
credential: true是必需的吗? -
不知道,推荐的教程太多了