【前端開發】跨域請求如何攜帶cookie


前言

閱讀本文,你將學到:

1.學會`withCredentials`屬性;
2.學會`axios`配置`withCredentials`;
3.學會設置`Access-Control-Allow-Origin`屬性;
4.學會設置`Access-Control-Allow-Credentials`屬性;
5.學會解決跨域請求攜帶源站cookie的問題;

思路:

  1. 使用express搭建第一個服務A(http://localhost:8000),運行在8000端口上;

  2. A服務托管index.html(用於在前端頁面發送網絡請求)文件;

  3. A服務中寫一個處理請求的路由,加載index.html頁面時,種下cookie(這里種cookie為了在請求B服務時攜帶上);

  4. 使用express搭建第二個服務B(http://localhost:8003),運行在8003端口上;

  5. A服務托管的index.html頁面去請求B服務,然后把cookie傳過去;

教程

前端修改如下

// 修改跨域請求的代碼
crossButton.onclick = function () {
    axios({
     withCredentials: true, // 前端增加設置這個
      method: "get",
      url: "http://localhost:8003/anotherService",
    }).then((res) => {
      console.log(res);
    });
};

后端修改

// 在所有路由前增加,可以攔截所有請求
app.all("*", (req, res, next) => {
 res.header("Access-Control-Allow-Origin", "http://localhost:8000");
  res.header("Access-Control-Allow-Credentials", "true"); 
  next();
});

 

總結

前端請求時在request對象中配置"withCredentials": true;

服務端在response的header中配置"Access-Control-Allow-Origin", "http://xxx:${port}";

服務端在response的header中配置"Access-Control-Allow-Credentials", "true"

 


免責聲明!

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



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