由於瀏覽器的安全限制,前端js代碼無法直接訪問不同域下的資源。只要協議、域名、端口有任何一個不同,都被當作是不同的域。
跨域的解決方案有很多,目前常用的方案是通過nginx代理服務器給返回的響應頭添加cors跨域配置項來解決。以下為配置示例:
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
add_header Access-Control-Allow-Credentials 'true';
add_header Access-Control-Allow-Headers 'DNT,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,token,Wecom-Cert,group,preview-user,X-Mx-ReqToken';
但關於add_header的使用,有一些注意事項,在此對nginx配置add_header進行說明:
Syntax:add_header name value [always];
Default:—
Context:http, server, location, if in location
Adds the specified field to a response header provided that the response code equals 200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13), or 308 (1.13.0). Parameter value can contain variables.
There could be several add_header directives. These directives are inherited from the previous configuration level if and only if there are no add_header directives defined on the current level.
If the always parameter is specified (1.7.5), the header field will be added regardless of the response code.
意思也就是說只有在響應狀態碼成功時,add_header 指令才生效,並且當前《作用域》下沒有 add_header 指令時,會向上層繼承。
在使用過程中難免會遇到上級指令被覆蓋的情況,如:
server {
add_header x-name nginx;
location / {
root /path;
}
location /static/ {
add_header x-name2 nginx2;
}
}
當匹配到 / 時,由於 location / 中沒有 add_header 指令,所以會繼承 server 中的 x-name ,而當匹配到 /static/ 時,由於內容已經有 add_header 指令,則上層的 x-name 不會被繼承,導致只會輸出 x-name2 。
實際工作中往往前端需要捕獲服務端異常響應,這時在nginx跨域add_header上加上always,使nginx對任何響應碼生效。
具體請參考nginx官方文檔:http://nginx.org/en/docs/http/ngx_http_headers_module.html