【发布时间】:2020-03-26 03:18:43
【问题描述】:
尽管在 SO 上阅读并实施了各种解决方案,但我在使用 CORS 时遇到问题。
我有一个使用 Express/NodeJS 作为 api 和 React JS 作为前端的应用程序。
在开发中,react 应用程序 http://localhost:3000 能够与 express 后端 http://localhost:9000 和 app.use(cors()) 对话。
现在我正在尝试在生产中使用这个应用程序。
这两个应用程序都保存在单独的 git 存储库中。 React 被部署为 aws s3 上的静态网站并且运行良好。 Node JS 部署在 Elastic Bean Stalk 上并处于就绪状态。 我有一个 Postgres SQL 数据库附加到我可以在 pgadmin4 中连接到的 ebs 实例(节点应用程序)。
两个应用在路由 53 myproject.com 中使用相同的基域。
两者都配置为侦听 https/443。我可以同时访问 URLhttps://myproject.com 和 https://api.myproject.com,它们看起来就像在我的 localhost 环境中一样。
当我尝试在我的网站上注册用户时,我遇到了这个错误:
Access to XMLHttpRequest at 'https://api.myproject.com/users/signup/' from origin 'https://myproject.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
两个应用程序都能够“看到”彼此,但这就是它的终点。 查看我的代码,我无法弄清楚问题发生在哪里:
server.js
const express = require('express');
const cors = require('cors');
const logger = require('morgan');
const bodyParser = require('body-parser');
require('dotenv').config();
const PORT = process.env.PORT || 9000; // DEV
const app = express();
const corsOptions = {
origin: 'https://myproject.com',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
const allowCrossDomain = function (req, res, next) {
res.header('Access-Control-Allow-Origin', 'https://myproject.com');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
app.use(cors());
const { userRouter } = require('./routes/userRouter');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(allowCrossDomain);
app.use((e, req, res, next) => {
res.header("Access-Control-Allow-Origin", "https://myproject.com");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
if (e) {
console.log(e);
res.status(500).send(e.message);
}
next();
});
app.use('/users', userRouter);
app.listen(PORT, () => {
console.log(`Express server is listening on PORT ${PORT}.`);
});// - TESTING
我尝试过的: 这些解决方案大部分来自这个 SO 帖子:Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?
只使用app.use(cors());
使用通配符 * 代替域名。
用 cors 将我的域列入白名单(来自这篇博文):https://daveceddia.com/access-control-allow-origin-cors-errors-in-react-express/
// Set up a whitelist and check against it:
var whitelist = ['https://myproject.com']
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
// Then pass them to cors:
app.use(cors(corsOptions));
我还按照另一个 StackOverflow 帖子中的建议将 app.use(cors()) 移到了我的路线上方。
在这一点上,我被困住了,所以任何帮助都非常感谢,所以在此先感谢。
【问题讨论】:
-
您使用的是什么版本的 express 和 cors?
-
响应的 HTTP 状态码是什么?您可以使用浏览器开发工具中的网络窗格进行检查。是 4xx 还是 5xx 错误而不是 200 OK 成功响应?
-
我实际上得到了 3 个单独的错误:#1
Failed to load resource: the server responded with a status of 404 ()、#2Failed to load resource: the server responded with a status of 504 (GATEWAY_TIMEOUT)& #3Access to XMLHttpRequest at 'https://api.myproject.com/users/signup/' from origin 'https://myproject.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
标签: node.js reactjs express cors