【发布时间】:2019-11-01 20:43:31
【问题描述】:
我有一个运行 Angular 应用程序的 Express 服务器(因为我需要服务器端渲染)。
问题是我第一次从应用程序发出请求时一切正常。
当我导航到某个页面并返回请求正常工作的上一个页面时出现问题。当我返回请求不再起作用时,它会显示下一个错误:
从源访问“http://myserver/api/endpoint”处的 XMLHttpRequest 'http://localhost:4000' 已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。
我尝试使用 CORS 和其他东西,但它最终给了我同样的错误。
这是我使用 CORS 的部分:
const allowedOrigins = [
'http://localhost:4000',
'http://localhost:4200',
'http://myserver'
];
const corsOptions = {
origin: function(origin, callback) {
if (!origin) {
return callback(null, true);
}
if (allowedOrigins.indexOf(origin) === -1) {
const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
return callback(new Error(msg), false);
}
return callback(null, true);
},
credentials: true,
optionsSuccessStatus: 200,
methods: 'GET,PUT,POST,OPTIONS',
allowedHeaders: 'Content-Type,Authorization'
};
app.use(cors(corsOptions));
在没有 CORS 的情况下也尝试过:
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-Type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
那么,第一次有效,第二次无效可能是什么问题?
这是否与快速控制台中的此错误有关:'ERROR TypeError: spanEl.getBoundingClientRect is not a function'?
【问题讨论】:
-
在所有行中使用
res.setHeader而不是res.header还添加Authorization -
@JoelJoseph 试过了,没用