溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

javascript怎么在跨域請求中攜帶cookie

發(fā)布時間:2022-03-02 12:30:57 來源:億速云 閱讀:927 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)javascript怎么在跨域請求中攜帶cookie的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

1. 搭建環(huán)境

1.生成工程文件

npm init

2.安裝 express

npm i express --save

3.新增app1.js,開啟服務(wù)器1 端口:3001

const express = require('express')
const app = express()
const port = 3001

// 設(shè)置`cookie`
app.get("/login", (req, res) => {
    res.cookie("JESSIONID", "10101001", { maxAge: 2000000, httpOnly: true });
    res.json({ code: 200, message: "登錄成功" });
  });
  
// 檢測瀏覽器是否會自動攜帶上`cookie`
app.get("/getUser", (req, res) => {
const user = req.headers.cookie.split("=")[1];
res.json({ code: 200, user });
});

// 靜態(tài)資源在public目錄下
app.use("/", express.static("public"));
  
app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

4.新增app2.js,開啟服務(wù)器2 端口:3002

const express = require('express')
const app = express()
const port = 3002

app.get("/crossList", (req, res) => {
  res.json({ code: 200, msg: "這是3002端口返回的" });
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

5.新增public文件夾,新建index.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
    <div>
        <button id="button">同源請求</button>
        <button id="crossButton">跨域請求</button>
    </div>
    <script>
        const button = document.querySelector("#button");
        const crossButton = document.querySelector("#crossButton");
  
        axios.get("http://localhost:3001/login", {}).then((res) => {
          console.log(res);
        });
        // 發(fā)送同域請求
        button.onclick = function () {
          axios.get("http://localhost:3001/getUser", {}).then((res) => {
            console.log(res);
          });
        };
        // 發(fā)送跨域請求
        crossButton.onclick = function () {
          axios({
            method: "get",
            url: "http://localhost:3002/crossList",
          }).then((res) => {
            console.log(res);
          });
        };
      </script>
  
</body>
</html>

6.分別啟動兩個服務(wù)

  • node app1.js

  • node app2.js

7.項目目錄如下

javascript怎么在跨域請求中攜帶cookie

至此,環(huán)境搭建好了,在瀏覽器訪問http://localhost:3001/index.html即可。

javascript怎么在跨域請求中攜帶cookie

我們把資源部署到了服務(wù)器1上,即端口3001。同源請求的是3001的接口,跨域請求的是3002的接口。

2. 測試同源cookie

加載index.html會自動請求login接口,獲取cookie

javascript怎么在跨域請求中攜帶cookie

javascript怎么在跨域請求中攜帶cookie

點(diǎn)擊同源請求按鈕,發(fā)送同源請求,getUser接口請求會自動攜帶cookie

javascript怎么在跨域請求中攜帶cookie

3. 跨域請求攜帶cookie

點(diǎn)擊跨域請求按鈕

javascript怎么在跨域請求中攜帶cookie

解決:
1.axios請求時加上 withCredentials: true,再次點(diǎn)擊跨域請求

crossButton.onclick = function () {
  axios({
     withCredentials: true, // ++
     method: "get",
     url: "http://localhost:3002/crossList",
   }).then((res) => {
     console.log(res);
   });
 };

javascript怎么在跨域請求中攜帶cookie

2. 在服務(wù)端設(shè)置Access-Control-Allow-Origin
在app2.js中加入

app.all("*", (req, res, next) => {
   res.header("Access-Control-Allow-Origin", "http://localhost:3001");  // ++
   next();
});

javascript怎么在跨域請求中攜帶cookie

3. 在服務(wù)端設(shè)置Access-Control-Allow-Credentials
在app2.js中加入

app.all("*", (req, res, next) => {
   res.header("Access-Control-Allow-Origin", "http://localhost:3001");
   res.header("Access-Control-Allow-Credentials", "true"); // ++ 
   next();
});

javascript怎么在跨域請求中攜帶cookie

到此,我看可以看到跨域請求中加上了cookie。

4. 總結(jié)

1.前端請求時在request對象中配置"withCredentials": true;
2.跨域服務(wù)端在response的header中配置"Access-Control-Allow-Origin", “http://xxx:${port}”;
3.跨域服務(wù)端在response的header中配置"Access-Control-Allow-Credentials", “true”

5. 知識點(diǎn)

1.withCredentials
該XMLHttpRequest.withCredentials屬性是一個布爾值,指示是否Access-Control應(yīng)使用 cookie、授權(quán)標(biāo)頭或 TLS 客戶端證書等憑據(jù)進(jìn)行跨站點(diǎn)請求。設(shè)置withCredentials對同站點(diǎn)請求沒有影響。
此外,此標(biāo)志還用于指示何時在響應(yīng)中忽略 cookie。默認(rèn)值為false. XMLHttpRequest來自不同域的 cookie 不能為自己的域設(shè)置 cookie 值,除非在發(fā)出請求之前withCredentials設(shè)置為。true通過設(shè)置為 true 獲得的第三方 cookiewithCredentials仍將遵循同源策略,因此請求腳本無法通過document.cookie或從響應(yīng)標(biāo)頭訪問。 &mdash;來自MDN

2.Access-Control-Allow-Origin
指定了該響應(yīng)的資源是否被允許與給定的origin共享

3.Access-Control-Allow-Credentials
當(dāng)請求的憑證模式 ( ) 為Access-Control-Allow-Credentials時,響應(yīng)標(biāo)頭告訴瀏覽器是否將響應(yīng)暴露給前端 JavaScript 代碼。 Request.credentialsinclude

當(dāng)請求的憑據(jù)模式 ( Request.credentials) 為 時,如果值為include,瀏覽器只會將響應(yīng)暴露給前端 JavaScript 代碼。 Access-Control-Allow-Credentialstrue

憑據(jù)是 cookie、授權(quán)標(biāo)頭或 TLS 客戶端證書。

當(dāng)用作對預(yù)檢請求的響應(yīng)的一部分時,這表明是否可以使用憑證發(fā)出實際請求。請注意,簡單GET 的請求不會被預(yù)檢。因此,如果對具有憑據(jù)的資源發(fā)出請求,并且如果此標(biāo)頭未與資源一起返回,則響應(yīng)將被瀏覽器忽略并且不會返回到 Web 內(nèi)容。
Access-Control-Allow-Credentials頭與 XMLHttpRequest.withCredentials屬性或 Fetch API 構(gòu)造函數(shù)中的credentials選項一起使用。Request()對于帶有憑據(jù)的 CORS 請求,為了讓瀏覽器向前端 JavaScript 代碼公開響應(yīng),服務(wù)器(使用 Access-Control-Allow-Credentials標(biāo)頭)和客戶端(通過為 XHR、Fetch 或 Ajax 請求設(shè)置憑據(jù)模式)都必須表明它們&rsquo;正在選擇包括憑據(jù)。

感謝各位的閱讀!關(guān)于“javascript怎么在跨域請求中攜帶cookie”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI