在Express,React,Cors,Cookie中使用抓取-'Access-Control-Allow-Origin'标头

时间:2020-08-11 13:33:38

标签: reactjs express cors fetch csrf

花了很多时间试图解决这个问题,但没有成功。我正在尝试使用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}`);
});

1 个答案:

答案 0 :(得分:0)

const char *中间件功能在csrfMiddleware中间件之前被调用。

它抛出cors,从而阻止ForbiddenError: invalid csrf token中间件向响应添加标头。

您可以通过将cors中间件放在首位来解决此问题。

cors
相关问题