首页 > 解决方案 > 通过获取请求访问服务器时,express JS cors 中间件不起作用

问题描述

服务器位于http://localhost:3001,客户端相同,但端口为 3000。

在客户端我运行简单的获取,我需要从服务器获取登录的用户数据,目前我只是使用 GET 方法(GET,POST,没有工作)这样做(我还必须包括 cookie):

fetch("http://localhost:3001/user", {
      method: "GET",
      credentials: "include",
      headers: {
        "Content-Type": "application/json"
      }
    }).then(response => {
      console.log(response);
    });

和服务器:

const cors = require("cors");
var corsOptions = {
  origin: "http://localhost:3000",
  optionsSuccessStatus: 200
};
app.get("/user", cors(corsOptions), function(req, res, next) {
  u_session = req.session;
  const db_result = db
    .collection("users")
    .findOne({ email: u_session.email }, function(err, result) {
      if (err) throw err;

      res.json({ email: result.email, type: result.type });
    });
});

我得到的是cors错误:

Access to fetch at 'http://localhost:3001/user' from origin 'http://localhost:3000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

另外,如果我通过浏览器访问服务器 URL,我可以看到 access-allow-control-allow-origin 标头设置成功。

样本

也应要求,失败案例网络选项卡的屏幕截图: 在此处输入图像描述

我在互联网上搜索了很多解决方案,似乎没有任何效果。我错过了什么吗?

谢谢你的帮助。

标签: node.jsexpresscors

解决方案


如果您有一个代理集,请确保它被设置为http://localhost:3001. 之后调整你fetch只使用部分网址,如下所示:

fetch("/user", {
      method: "GET",
      headers: {
        "Content-Type": "application/json"
      }
    }).then(response => {
      console.log(response);
    });

删除它也应该是安全的:

const cors = require("cors");
var corsOptions = {
  origin: "http://localhost:3000",
  optionsSuccessStatus: 200
};

推荐阅读