跨域請求問題總結

XMLHttpRequest.withCredentials

  • 是boolean類型,默認值是false
  • 他指示了是否使用資格證書來建立一個跨站點訪問控制(cross-site Access-Control),同一個站點下該參數無效。
  • 其中資格證書有:cookie、authorization headers(頭部受權)或TLS客戶端證書等

實踐

前提:跨域狀況(同域下無效)vue

使用vue的代理proxy

vue項目中使用proxy代理服務,會轉爲同域,設置withCredentials=true,將不會形成影響,但發佈到服務器出現跨域,將沒法訪問服務端接口,所以發佈服務器不要採用代理。後端

設置withCredentials=true

一、Access-Control-Allow-Origin不能爲*,不然將報錯,以下:跨域

Failed to load http://localhost:3000/login: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'https://192.168.125.15:9527' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.服務器

解決辦法:須要在後端增長Access-Control-Allow-Origin的須要跨域地址cookie

二、配合Access-Control-Allow-Credentials一塊兒使用,不然將報錯,以下:

Failed to load http://localhost:3000/login: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. Origin 'https://192.168.125.15:9527' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. 解決辦法:增長Access-Control-Allow-Credentialsapp

headers中增長自定義參數

響應首部Access-Control-Allow-Headers用於預檢請求中列出將會在正式請求Access-Control-Request-Headers中容許的信息url

注意如下這些特定的首部是一直容許的:Accept, Accept-Language, Content-Language, Content-Type (但只在其值屬於 MIME 類型 application/x-www-form-urlencoded, multipart/form-data 或 text/plain中的一種時)。這些被稱做simple headers,你無需特地聲明它們。3d

實踐

  • 添加自定義頭部變量token,Access-Control-Allow-Headers中並無添加容許的token將會報錯

Failed to load http://localhost:3000/login: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.代理

  • 解決辦法:後端增長Access-Control-Allow-Headers的token配置

相關文章
相關標籤/搜索