如下
server{
listen 80;
server_name www.b.com;
location / {
add_header "Access-Control-Allow-Origin" "http://www.a.com";
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS";
add_header "Access-Control-Allow-Headers" "X-Requested-With, access_token";
add_header "Access-Control-Allow-Credentials" "true";
add_header "Access-Control-Expose-Headers" "Date";
if ($request_method = 'OPTIONS') {
add_header "Access-Control-Allow-Origin" "http://www.a.com";
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS";
add_header "Access-Control-Allow-Headers" "X-Requested-With, acces_token";
add_header "Content-Type" "text/plain charset=UTF-8";
add_header "Content-Length" 0;
add_header "Access-Control-Max-Age" 1728000;
return 204;
}
proxy_pass http://localhost:8080/;
}
}
Access-Control-Allow-Origin
允许那个域名使用当前域名资源,例如:http://www.a.com
就表示B网站www.b.com
的资源(API)允许A网站访问。如果使用了*号,那就表示允许所有网站使用www.b.com
的资源。这里只能一次写一个域名,不能使通配符。例如你只能写 http://www.a.com, http://src.a.com
,而不允许写http://*.a.com
。甚到不能省略协议,如果用到https
还得另外写,例如http://www.a.com, https://www.a.com
。
Access-Control-Allow-Methods
允许调用的方法,顾名思意,就是允许何种请求方式访问B服务器的资源了。
Access-Control-Allow-Headers
允许请求时附带的头部信息,例如你发送请求时需要发送access_token头部信息,用于获取用户信息,那么你就得必须加上这个语句。
Access-Control-Allow-Credentials
如果希望调用接口时附带cookie,那么除了要在 XMLHttpRequest 实例中,withCredentials 要设为 true,这样浏览器才会在请求时带上cookie,另外,还要在服务器设置 Access-Control-Allow-Credentials: true,这样浏览器在接收到服务器的返回时,浏览器才会把结果告诉回 XMLHttpRequest 实例。
Access-Control-Expose-Headers
允许暴露给WEB页面的头部信息,例如JS有时需要获取服务器返回的Date头,用于校对当前页面的时间,那么就需要加上Date。
prefight
当发送ajax请求之前,浏览器会预先发送一个options的请求,用于询问是否允许接下来的ajax请求,如果允许则继续发送,否则就告诉浏览器截止ajax请求,这种行为我们称之为prefight。prefight的cors头与其它get、post的是一样,只是返回时会加大缓存时间,减少不必要的请求,并且直接返回空内容Content-Length:0和Status-Code:204。
Q.E.D.