【问题标题】:Express CORS request with axios fails使用 axios 的 Express CORS 请求失败
【发布时间】:2022-01-23 13:06:04
【问题描述】:

我有一个身份验证 cookie,我想发送到快速服务器。该请求应该从 localStorage(它确实如此)发送 JWT 和先前设置的 cookie。

cookie 由来自端点的以下响应设置:

 res
    .cookie("cookiename", "cookievalue", {
      maxAge: 86400 * 1000, 
      httpOnly: false, 
      secure: false, 
    })
    .sendStatus(200);

cookie 在 DevTools 中正确显示:

然后,我想在每个后续请求中使用 cookie: 首先我将 withCredentials 全局设置为 true:

axios.defaults.withCredentials = true;

然后我发出一个发送 cookie 的请求:

axios
      .get("http://localhost:5000/userLikedPlaces", {
        headers: {
          jwt: localStorage.getItem("jwt"),
          "X-Requested-With": "XMLHttpRequest",
          "Content-Type": "application/json",
          "Access-Control-Allow-Credentials": true,
        },
        params: { limit: likedQueryOffset },
      })

但是,我收到一个错误:

据我了解,我应该将Access-Control-Allow-Origin设置为我的localhost:3000地址,所以我复制以下代码:

  server.use(function (req, res, next) {
  // Website you wish to allow to connect
  res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");

  // Request methods you wish to allow
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, OPTIONS, PUT, PATCH, DELETE"
  );

  // Request headers you wish to allow
  res.setHeader(
    "Access-Control-Allow-Headers",
    "X-Requested-With,content-type"
  );

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader("Access-Control-Allow-Credentials", true);

  // Pass to next layer of middleware
  next();
});

其他中间件有:

server.use(cors());
server.use(cookieParser("MySecret"));
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json({ limit: "10kb" }));
server.use(cors({ credentials: true, origin: "http://localhost:3000" }));

我相当困惑,因为我已经查看了相当多的类似问题,而且这个标题似乎解决了这个问题,但显然不是在这里。 我的问题是如何解决 CORS 问题,将 cookie 从 localhost:3000(client) 获取到 localhost:5000(server)?

【问题讨论】:

    标签: node.js reactjs express cookies axios


    【解决方案1】:

    问题在于 CORS 中间件的默认配置使用通配符属性,这也是所有请求都被阻止的原因。解决方案是使用自定义配置:

    server.use(cors({ credentials: true, origin: "http://localhost:3000" }));
    

    【讨论】:

      猜你喜欢
      • 2020-07-08
      • 1970-01-01
      • 2019-02-19
      • 2020-11-26
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      相关资源
      最近更新 更多