在https://api.adshacker.com/上运行nodejs应用程序,并在https://adshacker.com/
上运行角度4开发其前端我遇到了问题。它有时有效,有时则无效。得到此错误
无法加载https://api.adshacker.com/ad:对预检的响应 请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许来源“https://adshacker.com” 访问。响应具有HTTP状态代码502.
为了观察它,您可以https://adshacker.com/并尝试更改页面并查看控制台。
我在nodejs app上的cors代码是
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Accept, clientId, clientSecret, access_token, refresh_token');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.status(200).send({});
} else {
next();
}
};
app.use(allowCrossDomain);
使用nginx托管在谷歌云中。
nginx服务器代码是
server {
server_name api.adshacker.com;
underscores_in_headers on;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
proxy_pass http://adshacker;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
#add_header 'Access-Control-Allow-Origin' '*';
}
}
从浏览器检查器我找到了以下网络呼叫响应