【发布时间】: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