javascript fetch 跨域請求時 session失效問題


javascript 使用fetch進行跨域請求時默認是不帶cookie的,所以會造成 session失效。

fetch(url, {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: JSON.stringify({
      data: options.data
    })
  })
credentials: 'include' 可以是fetch 帶上cookie。但是問題了來。
原來在服務器端設置header (php 服務器)
    header("Access-Control-Allow-Origin: *");

會報錯:

A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:8000' is therefore not allowed access.

可以看到不允許 使用‘*’ 號了,那么就改成 訪問域名(這里是本地調用所以是 http://localhost:8000)

header("Access-Control-Allow-Origin: http://localhost:8000");

改完后再次發送請求,還是報錯

Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://localhost:8000' is therefore not allowed access.

說'Access-Control-Allow-Credentials 頭必須是true,那么繼續增加

header("Access-Control-Allow-Credentials: true");

增加完后可以正常訪問了,而且session也有了。

 

ps: fetch 有個mode 是no-cors ,發現設置后返回的status是0,查資料后

no-cors mode is only to CDN content, such as scripts, CSS and image, you cannot be used for getting data,response.status = 0 is right behavior

no-cors 模式只能用來獲取CDN內容,比如腳本,css文件和圖片,如果用來獲取數據比如json格式就會返回status=0

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM