【发布时间】:2020-12-20 15:16:40
【问题描述】:
我有一个网站https://example.com,它在加载时应该从另一个网站https://subdomain.example.com:8080 获取数据,但显然我的请求被阻止了。附件是我在浏览器的网络选项卡中看到的内容。请求从浏览器端到 subdomain.example.com 的代理。我需要什么 CORS 标头?我不熟悉 CORS,我尝试在线阅读文档和示例但无济于事。
【问题讨论】:
我有一个网站https://example.com,它在加载时应该从另一个网站https://subdomain.example.com:8080 获取数据,但显然我的请求被阻止了。附件是我在浏览器的网络选项卡中看到的内容。请求从浏览器端到 subdomain.example.com 的代理。我需要什么 CORS 标头?我不熟悉 CORS,我尝试在线阅读文档和示例但无济于事。
【问题讨论】:
https://example.com 被阻止,因为 https://subdomain.example.com:8080 不允许。
拥有https://subdomain.example.com:8080 的人必须在允许的服务器源中添加https://example.com。
https://example.com 和 https://subdomain.example.com:8080 在 CORS 方面的处理方式不同。
例如,在 nodejs express 代码中,这是添加 CORS 并允许源服务器的方式。
在我的示例中,http://localhost:8080 将替换为 https://example.com
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8080");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
完整代码-
const bodyParser = require('body-parser')
const path = require('path');
const express = require('express');
const app = express();
const modelRoute = require('./model');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(express.static('dist'));
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8080");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/api/getData', modelRoute.getData);
app.post('/api/postData', modelRoute.postData);
app.listen(process.env.PORT || 8080, () => console.log(`Listening on port ${process.env.PORT || 8080}!`));
可能有两个级别的 CORS 启用,一个在 Nginx 端,另一个在 https://subdomain.example.com。
首先,您需要在全局级别或本地服务器部分的 nginx.conf 中添加以下标头。 nginx.conf 可能已经有这个头文件,那么你也需要添加它。
add_header Access-Control-Allow-Origin https://example.com;
更重要的是,首先,您需要查看 nginx.conf 是什么以及如何配置的。基于此,如果在 nginx.conf 中启用了 CORS,您也可以在 /location 部分中添加此标头。
这是一个样本
# local node.js server
upstream websocket {
server 127.0.0.1:3000;
}
server {
server_name ...;
# ...;
# add the header here
add_header Access-Control-Allow-Origin https://example.com;
location /path/ {
proxy_hide_header 'Access-Control-Allow-Origin';
}
}
请求可能会因为 nginx 端的其他标头而被阻塞。如果以上不起作用。您需要查看 nginx.conf 有哪些额外的标头。对于exm -
add_header 'Access-Control-Allow-Origin' 'http://api.localhost';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';
它很容易配置,但可能需要一些时间来试验。
您也可以查看以下线程。它可能会帮助您了解更多。
NGINX Reverse Proxy and Access-Control-Allow-Origin issue
How to enable CORS in Nginx proxy server?
如果 nginx.conf 看起来不错,但它仍然不起作用,那么只有您跳转到子域网站配置。这将节省您的时间。
【讨论】: