這篇文章給大家分享的是有關javascript怎么在跨域請求中攜帶cookie的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
1.生成工程文件
npm init
2.安裝 express
npm i express --save
3.新增app1.js,開啟服務器1 端口:3001
const express = require('express')
const app = express()
const port = 3001
// 設置`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 });
});
// 靜態資源在public目錄下
app.use("/", express.static("public"));
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})4.新增app2.js,開啟服務器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);
});
// 發送同域請求
button.onclick = function () {
axios.get("http://localhost:3001/getUser", {}).then((res) => {
console.log(res);
});
};
// 發送跨域請求
crossButton.onclick = function () {
axios({
method: "get",
url: "http://localhost:3002/crossList",
}).then((res) => {
console.log(res);
});
};
</script>
</body>
</html>6.分別啟動兩個服務
node app1.js
node app2.js
7.項目目錄如下

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

我們把資源部署到了服務器1上,即端口3001。同源請求的是3001的接口,跨域請求的是3002的接口。
加載index.html會自動請求login接口,獲取cookie


點擊同源請求按鈕,發送同源請求,getUser接口請求會自動攜帶cookie

點擊跨域請求按鈕

解決:
1.axios請求時加上 withCredentials: true,再次點擊跨域請求
crossButton.onclick = function () {
axios({
withCredentials: true, // ++
method: "get",
url: "http://localhost:3002/crossList",
}).then((res) => {
console.log(res);
});
};
2. 在服務端設置Access-Control-Allow-Origin
在app2.js中加入
app.all("*", (req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://localhost:3001"); // ++
next();
});
3. 在服務端設置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();
});
到此,我看可以看到跨域請求中加上了cookie。
1.前端請求時在request對象中配置"withCredentials": true;
2.跨域服務端在response的header中配置"Access-Control-Allow-Origin", “http://xxx:${port}”;
3.跨域服務端在response的header中配置"Access-Control-Allow-Credentials", “true”
1.withCredentials
該XMLHttpRequest.withCredentials屬性是一個布爾值,指示是否Access-Control應使用 cookie、授權標頭或 TLS 客戶端證書等憑據進行跨站點請求。設置withCredentials對同站點請求沒有影響。
此外,此標志還用于指示何時在響應中忽略 cookie。默認值為false. XMLHttpRequest來自不同域的 cookie 不能為自己的域設置 cookie 值,除非在發出請求之前withCredentials設置為。true通過設置為 true 獲得的第三方 cookiewithCredentials仍將遵循同源策略,因此請求腳本無法通過document.cookie或從響應標頭訪問。 —來自MDN
2.Access-Control-Allow-Origin
指定了該響應的資源是否被允許與給定的origin共享
3.Access-Control-Allow-Credentials
當請求的憑證模式 ( ) 為Access-Control-Allow-Credentials時,響應標頭告訴瀏覽器是否將響應暴露給前端 JavaScript 代碼。 Request.credentialsinclude
當請求的憑據模式 ( Request.credentials) 為 時,如果值為include,瀏覽器只會將響應暴露給前端 JavaScript 代碼。 Access-Control-Allow-Credentialstrue
憑據是 cookie、授權標頭或 TLS 客戶端證書。
當用作對預檢請求的響應的一部分時,這表明是否可以使用憑證發出實際請求。請注意,簡單GET 的請求不會被預檢。因此,如果對具有憑據的資源發出請求,并且如果此標頭未與資源一起返回,則響應將被瀏覽器忽略并且不會返回到 Web 內容。
Access-Control-Allow-Credentials頭與 XMLHttpRequest.withCredentials屬性或 Fetch API 構造函數中的credentials選項一起使用。Request()對于帶有憑據的 CORS 請求,為了讓瀏覽器向前端 JavaScript 代碼公開響應,服務器(使用 Access-Control-Allow-Credentials標頭)和客戶端(通過為 XHR、Fetch 或 Ajax 請求設置憑據模式)都必須表明它們’正在選擇包括憑據。
感謝各位的閱讀!關于“javascript怎么在跨域請求中攜帶cookie”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。