1. 程式人生 > >CORS 中的POST+JSON請求會先發送一個不帶Cookie的OPTIONS(preflight request)請求

CORS 中的POST+JSON請求會先發送一個不帶Cookie的OPTIONS(preflight request)請求

 
  1. var req = new XMLHttpRequest();

  2. req.open('post', 'http://127.0.0.1:3001/user', true);

  3. req.setRequestHeader('Content-Type', 'application/json');

  4. req.send('{"name":"tobi","species":"ferret"}');

此Ajax 跨域訪問post 請求,但是在伺服器卻得到的總是options請求 (req.method==‘OPTIONS’) 不知為何啊?

原因:

因為此post請求的 content-type不是one of the “application/x-www-form-urlencoded, multipart/form-data, or text/plain”, 所以Preflighted requests被髮起。“preflighted” requests first send an HTTP OPTIONS request header to the resource on the other domain, in order to determine whether the actual request is safe to send.然後得到伺服器response許可之後,res.set(‘Access-Control-Allow-Origin’, ‘

http://127.0.0.1:3000’);res.set(‘Access-Control-Allow-Methods’, ‘GET, POST, OPTIONS’);res.set(‘Access-Control-Allow-Headers’, ‘X-Requested-With, Content-Type’);再發起其post請求。https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

 

 

查詢原因是瀏覽器對簡單跨域請求和複雜跨域請求的處理區別。

XMLHttpRequest會遵守同源策略(same-origin policy). 也即指令碼只能訪問相同協議/相同主機名/相同埠的資源, 如果要突破這個限制, 那就是所謂的跨域, 此時需要遵守CORS(Cross-Origin Resource Sharing)機制。

那麼, 允許跨域, 不就是服務端設定Access-Control-Allow-Origin: *就可以了嗎? 普通的請求才是這樣子的, 除此之外, 還一種叫請求叫preflighted request。

preflighted request在傳送真正的請求前, 會先發送一個方法為OPTIONS的預請求(preflight request), 用於試探服務端是否能接受真正的請求,如果options獲得的迴應是拒絕性質的,比如404\403\500等http狀態,就會停止post、put等請求的發出。

那麼, 什麼情況下請求會變成preflighted request呢? 

1、請求方法不是GET/HEAD/POST
2、POST請求的Content-Type並非application/x-www-form-urlencoded, multipart/form-data, 或text/plain
3、請求設定了自定義的header欄位

上面請求中設定了自定義的headers欄位,出現了option請求。把自定義headers欄位刪掉後,只剩下get請求:

 

[javascript] view plain copy

  1. ajaxRequestGet: function (lastPath, requestParams, successFun) {  
  2.             $.ajax({  
  3.                 url : this.baseUrl+lastPath,  
  4.                 type : "get",  
  5.                 data: requestParams,  
  6.                 success : function(data){  
  7.                     successFun(data);  
  8.                 }  
  9.             });  
  10.         },