首页 > 解决方案 > 我还需要使用 CORS 吗?

问题描述

我正在开发 Web 应用程序的后端,我已经为任何路线设置了全局标头,如下所示

Router.js 文件

Router.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, Accept, Accept-Version,Set-Cookie, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Response-Time, X-PINGOTHER, X-CSRF-Token,Authorization"
  );
  res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
  res.header("Content-Type", "application/json");
  res.header("Access-Control-Allow-Credentials", true);
  next();
});

服务器.js

//user defined middlewares
app.use("/",Router);

我是否需要再次设置 cors,因为我已经允许从任何来源访问?,我也允许飞行前请求

标签: node.jsrestexpresscors

解决方案


/只有在请求服务的根目录时才会发送这些标头。对于任何其他端点,例如/getsomething不会设置 CORS 标头。

如果您的服务器的用例只是 root 访问 - 或者您需要仅为 root 访问设置 CORS 标头,那么 NO - 您无需执行任何操作。

但是,如果您有更多路由并且还需要它们与 CORS 兼容,那么您将不得不在所有路由之上使用通用中间件。

另一点是您的 CORS 中间件不应为OPTIONS预检请求发送任何其他内容。因此,最好在此处结束对OPTIONS请求的响应。

这是组合代码:

app.use((req, res, next) => {

  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, Accept, Accept-Version,Set-Cookie, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Response-Time, X-PINGOTHER, X-CSRF-Token,Authorization"
  );
  res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
  res.header("Content-Type", "application/json");
  res.header("Access-Control-Allow-Credentials", true);

  if (req.method === 'OPTIONS') 
    res.status(200).send();
  else
    next();     
});

推荐阅读