概述
MDN文檔 Cross-Origin Resource Sharing (CORS)
跨域的英文是Cross-Origin Resource Sharing (CORS),直譯過來就是:跨越了來源的源資共享。當瀏覽器上的頁面資源(http://www.a.com/xxx.html)試圖訪問其他域(http://www.b.com/xxx.html)時,瀏覽器會檢查兩個url的協議、域名、端口。其中任意一項不一致,都有可能產生跨域。
如上面例子中,http://www.a.com/xxx.html 和 http://www.b.com/xxx.html 的域名不同,就有可能會觸發跨域。
簡單請求
為什么說有可能會觸發,這是因為簡單請求不會觸發跨域。簡單請求是同時滿足以下條件的請求:
Some requests don't trigger a CORS preflight. Those are called simple requests, though the Fetch spec (which defines CORS) doesn't use that term. A simple request is one that meets all the following conditions:
One of the allowed methods:
Apart from the headers automatically set by the user agent (for example,
Connection
,User-Agent
, or the other headers defined in the Fetch spec as a forbidden header name), the only headers which are allowed to be manually set are those which the Fetch spec defines as a CORS-safelisted request-header, which are:
Accept
Accept-Language
Content-Language
Content-Type
(but note the additional requirements below)The only allowed values for the
Content-Type
header are:
application/x-www-form-urlencoded
multipart/form-data
text/plain
If the request is made using an
XMLHttpRequest
object, no event listeners are registered on the object returned by theXMLHttpRequest.upload
property used in the request; that is, given anXMLHttpRequest
instancexhr
, no code has calledxhr.upload.addEventListener()
to add an event listener to monitor the upload.No
ReadableStream
object is used in the request.
注意,不同瀏覽器對簡單請求的判斷條件會有細微不一致(不過這對后端開發人員來說,並不重要了)。
跨域解決方案
概述
在前后端分離的情景下,跨域是很常見的情景。前端部署在一台服務器(10.3.12.31)上,后端部署在另一台服務器(10.3.12.32)上,當用戶在瀏覽器中獲取並打開前端服務器的網頁資源后,若用戶通過網頁發任意請求到后端服務器,瀏覽器會檢測到網頁資源的域和請求資源的域不同,就有可能觸發跨域。

此時,瀏覽器若判定當前情景跨域,則會先發送一個預檢請求(preflight)給后端服務器,該請求的類型為OPTION
。預檢請求會告訴后端服務器真實請求的各種信息,來讓后端服務器判斷是否讓這個真實請求獲取資源。
預檢請求示例:

預檢請求響應示例:

真實請求示例:

在本示例中,后端服務器允許了預檢請求中的各種條件,所以真實請求能夠順利地發送給后端服務器並得到響應。更詳細的跨域請求Headers、響應Headers參考見MDN文檔 Cross-Origin Resource Sharing (CORS).
整體流程如下:

SpringBoot配置
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsWebFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
Nginx配置
若前端並不是將請求直接發送給后端,而是先發送給Nginx服務器,然后再由Nginx將請求轉發給后端,則應該給Nginx增加跨域配置。
轉自:我也說說Nginx解決前端跨域問題,正確的Nginx跨域配置(后端Nginx CORS跨域配置、CORS設置,后端允許跨域請求)
location /aoda-web {
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
root html;
index index.html index.htm;
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5;
}
跨域相關的配置,主要是下面這部分:
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
下面簡單講解一下,以便大家配置成功!
1、Access-Control-Allow-Origin,這里使用變量 $http_origin取得當前來源域,大家說用“*”代表允許所有,我實際使用並不成功,原因未知;
2、Access-Control-Allow-Credentials,為 true 的時候指請求時可帶上Cookie,自己按情況配置吧;
3、Access-Control-Allow-Methods,OPTIONS一定要有的,另外一般也就GET和POST,如果你有其它的也可加進去;
4、Access-Control-Allow-Headers,這個要注意,里面一定要包含自定義的http頭字段(就是說前端請求接口時,如果在http頭里加了自定義的字段,這里配置一定要寫上相應的字段),從上面可看到我寫的比較長,我在網上搜索一些常用的寫進去了,里面有“web-token”和“app-token”,這個是我項目里前端請求時設置的,所以我在這里要寫上;
5、Access-Control-Expose-Headers,可不設置,看網上大致意思是默認只能獲返回頭的6個基本字段,要獲取其它額外的,先在這設置才能獲取它;
6、語句“ if ($request_method = 'OPTIONS') { ”,因為瀏覽器判斷是否允許跨域時會先往后端發一個 options 請求,然后根據返回的結果判斷是否允許跨域請求,所以這里單獨判斷這個請求,然后直接返回。