【问题标题】:CORS on server header服务器标头上的 CORS
【发布时间】:2019-04-10 08:48:30
【问题描述】:

我正在为 Netlify 部署一个简单的节点服务器和一个 React 应用程序。 React App 向服务器发出 API 请求,并在 2.8.5 版本中通过 const cors = require("cors"); 使用 cors。

一开始我指定了以下(server.js)

app.use(
  cors({
    origin: CLIENT_ORIGIN
  })
);

这似乎只是告诉服务器“我正在使用 CORS”,但没有专门设置任何标头或允许任何列入白名单的网站访问服务器。然后我在我的开发环境中的 .env 文件中设置CLIENT_ORIGIN,并通过 Netlify 上的Build environment variables。我为服务器和前端部署了一个新版本,但是我一定是在某个地方弄错了:

Access to fetch at 'https://serverUrl.com/example/get' from origin 
'https://react-app-example.com' has been blocked by CORS policy: 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.

然后我尝试设置:

app.use(function(req, res, next) {
  res.header(
    "Access-Control-Allow-Origin",
    "https://react-app-example.com"
  );
  res.header("Access-Control-Allow-Headers", "Content-Type,Authorization");
  res.header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE");
  if (req.method === "OPTIONS") {
    return res.sendStatus(204);
  }
  next();
});

这也不起作用。错误消息保持不变。让我感到厌烦的是,几个月前我有一个类似的东西,它的构建非常相似,但仍然保留在 heroku 上。与上述相同的方法没有问题。

我错过了什么?

【问题讨论】:

  • 您是否可以控制/访问处理您的请求的服务器端脚本?如果是这样,您应该在那里放置合适的标题。

标签: javascript node.js cors


【解决方案1】:

在尝试了各种方法后,我终于明白 Netlify 本身并不支持 Node 应用程序 (without extra tedious config)。

可以找到最接近的解决方案 here in another answer 或通过 Heroku 等其他服务。 我对 heroku 的主要问题是,当 dyno(在我的情况下是提供 API 路由的服务器)有一段时间没有被调用时,它会进入睡眠状态以节省资源,进而需要更长的时间来响应在第一次通话。还没有为提供 API 路由的 node/express 应用程序找到任何其他免费解决方案。

更新:Heroku 和 Netlify 不能很好地配合,除非您将以下 CORS 参数添加到后端:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", CLIENT_ORIGIN);
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  res.header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE");
  res.header("Access-Control-Allow-Credentials", true); <--- this is the only different line I added.
  if (req.method === "OPTIONS") {
    return res.sendStatus(204);
  }
  next();
});

然后通过fetch向前端请求以下内容:

fetch(`${API_BASE_URL}/dept/get/`, {
      method: 'GET',
      credentials: 'include', <-- this is the most important change
    })
      .then((res) => {...}

【讨论】:

    猜你喜欢
    • 2019-10-25
    • 2016-02-15
    • 2015-09-25
    • 2020-03-30
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 2017-12-21
    相关资源
    最近更新 更多