什么是CORS?
跨域资源共享(CORS)是一种机制,允许网页应用从不同的域请求资源。在浏览器中,由于同源策略的限制,通常不允许跨域请求。CORS通过在HTTP响应头中添加一些特定的字段,来允许跨域请求。
Nginx-基础跨域配置
nginx
server {
listen 80;
server_name your_domain.com;
location / {
add_header Access-Control-Allow-Methods *;
add_header Access-Control-Max-Age 3600;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers $http_access_control_request_headers;
}
}
Access-Control-Allow-Methods
: 指定在实际的请求中允许的方法。这里设置为*
表示允许任何方法,你也可以指定具体的HTTP方法,比如GET
,POST
等。Access-Control-Max-Age
: 指定预检请求的有效期(以秒为单位)。在这个例子中,设置为3600秒,即1小时。Access-Control-Allow-Credentials
: 指定是否允许发送Cookie。设置为true
表示允许。Access-Control-Allow-Origin
: 指定允许的源。这里使用*
表示允许任意的源,也可以设置为具体的域名。Access-Control-Allow-Headers
: 指定在实际请求中允许的头部。这里使用$http_access_control_request_headers
表示允许来自请求中的Access-Control-Request-Headers
头的值。- 如果请求方法是
OPTIONS
,则返回200。这是预检请求的响应。
Dataiku-Nginx的跨域配置
在 /home/dss/dss-home/install-support/nginx.conf
修改如下配置
nginx
location ^~ /dip/ {
add_header Access-Control-Allow-Methods *;
add_header Access-Control-Max-Age 3600;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Headers $http_access_control_request_headers;
if ($request_method = OPTIONS) {
return 200;
}
proxy_pass http://127.0.0.1:11201/dip/;
}
add_header Access-Control-Allow-Credentials
: 带Cookie的请求需要加上这个字段,并设置为trueadd_header Access-Control-Allow-Origin
: 动态获取请求客户端请求的域, 这里使用$http_origin
, 不用*
是因为带Cookie的请求不支持*
OPTIONS
预检命令,只有预检命令通过时才发送请求
Iframe 内嵌请求
在默认情况下,跨域请求不会发送凭证信息(如 Cookie、HTTP认证等)
- 发送登录请求
vue
const response = await fetch(dataikuUrl + '/dip/api/login' + '?login=' + admin + '&password=' + password, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'User-Agent': 'MyDataikuClient/1.0'
},
credentials: 'include'
});
credentials: 'include'
表示在跨域请求中包括凭证信息,比如在跨域请求中携带 Cookie。为了允许这些信息在跨域请求中传递,需要设置credentials
为'include'
。
- 添加iframe
vue
<div>
<iframe :src="http://your_domain.com:11200/projects/data_processor/dashboards/YRS5QEA_/view/5gqatVO?fullScreen=true" width="100%" height="100px" ></iframe>
</div>