如何解决在Express,React,Cors,Cookie中使用抓取-'Access-Control-Allow-Origin'标头
花了很多时间试图解决这个问题,但没有成功。我正在尝试使用cookie运行csurf保护。目前,我已尽可能简化以下代码。我正在运行从React到Express上另一台服务器的获取请求。它给出了错误:
“ CORS策略阻止从原点'http:// localhost:3000'访问'http:// localhost:3003 / testlogin'的访问:否'Access-Control-Allow-Origin'标头出现在所请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“ no-cors”以在禁用CORS的情况下获取资源。”
据我了解,“ access-Control-Allow-Origin”标头是在我的corsOptions中设置的。因此,它不应引发此错误。我显然缺少了一些东西。非常感谢您的帮助。
Express服务器:
select ASSETS,avg(case when indicatorname = 'X01' then IND_CALCS end) as ind_X01,avg(case when indicatorname = 'X02' then IND_CALCS end) as ind_X02,avg(case when indicatorname = 'X03' then IND_CALCS end) as ind_X03,. . .
from DB
where DB_DATETIME between cast('2020-08-08 19:00:00.0' as timestamp format 'YYYY-MM-DD HH:MI:SS.T') and cast('2020-08-10 23:59:59.0' as timestamp format 'YYYY-MM-DD HH:MI:SS.T')
group by ASSETS;
前端(反应):
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}`);
});
解决方法
const char *
中间件功能在csrfMiddleware
中间件之前被调用。
它抛出cors
,从而阻止ForbiddenError: invalid csrf token
中间件向响应添加标头。
您可以通过将cors
中间件放在首位来解决此问题。
cors
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。