花了很多时间想弄清楚这一点,但没有成功。我正试着用cookie让csurf保护运行。目前,我已经尽可能地简化了下面的代码。我正在Express上运行从React到另一台服务器的提取请求。它给出了错误:
“CORS策略阻止了在”http://localhost:3003/testlogin“从origin”http://localhost:3000“获取的访问:请求的资源上没有”access-control-allow-origin“标头。如果不透明的响应符合您的需要,请将请求的模式设置为”no-cors“以在禁用CORS的情况下获取资源。”
据我所知,'Access-Control-Allow-Origin'头是在我的CorsOptions中设置的。所以它不应该抛出这个错误。我显然错过了什么。感激地得到的任何帮助。
快速服务器:
const cookieParser = require("cookie-parser");
const cors = require('cors')
const express = require("express");
const csrf = require("csurf");
const app = express();
const csrfMiddleware = csrf({ cookie: true });
app.use(cookieParser());
const corsOptions = {
origin: 'http://localhost:3000',
methods: "GET,HEAD,POST,PATCH,DELETE,OPTIONS",
credentials: true,
allowedHeaders: "Content-Type, Authorization, X-Requested-With, Accept",
}
app.options('*', cors(corsOptions))
app.use(csrfMiddleware);
app.post("/testlogin", cors(corsOptions), (req, res) => {
console.log('test login reached', );
res.end(JSON.stringify({ status: "success" }));
});
const PORT = process.env.PORT || 3003;
app.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT}`);
});
前端(react):
function testClick() {
console.log("testClick Clicked");
let urlToGetUserProfile = 'http://localhost:3003/testlogin'
return fetch(urlToGetUserProfile, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
credentials: "include",
body: JSON.stringify({ idToken: "idTokengoeshere" }),
})
.then((fetchResponse) => {
console.log(fetchResponse);
})
}
在cors
中间件之前调用csrfmiddleware
中间件函数。
它抛出ForbiddenError:无效csrf令牌
,从而阻止CORS
中间件向响应添加头。
您可以通过将cors
中间件放在首位来解决这个问题。
app.use(cors(corsOptions));
app.use(csrfMiddleware);
app.post("/testlogin",(req, res) => {
console.log('test login reached', );
res.end(JSON.stringify({ status: "success" }));
});