詳解javascript如何在跨域請(qǐng)求中攜帶cookie
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: "登錄成功" });
});
// 檢測瀏覽器是否會(huì)自動(dòng)攜帶上`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">同源請(qǐng)求</button>
<button id="crossButton">跨域請(qǐng)求</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ā)送同域請(qǐng)求
button.onclick = function () {
axios.get("http://localhost:3001/getUser", {}).then((res) => {
console.log(res);
});
};
// 發(fā)送跨域請(qǐng)求
crossButton.onclick = function () {
axios({
method: "get",
url: "http://localhost:3002/crossList",
}).then((res) => {
console.log(res);
});
};
</script>
</body>
</html>
6.分別啟動(dòng)兩個(gè)服務(wù)
- node app1.js
- node app2.js
7.項(xiàng)目目錄如下

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

我們把資源部署到了服務(wù)器1上,即端口3001。同源請(qǐng)求的是3001的接口,跨域請(qǐng)求的是3002的接口。
2. 測試同源cookie
加載index.html會(huì)自動(dòng)請(qǐng)求login接口,獲取cookie


點(diǎn)擊同源請(qǐng)求按鈕,發(fā)送同源請(qǐng)求,getUser接口請(qǐng)求會(huì)自動(dòng)攜帶cookie

3. 跨域請(qǐng)求攜帶cookie
點(diǎn)擊跨域請(qǐng)求按鈕

解決:
1.axios請(qǐng)求時(shí)加上 withCredentials: true,再次點(diǎn)擊跨域請(qǐng)求
crossButton.onclick = function () {
axios({
withCredentials: true, // ++
method: "get",
url: "http://localhost:3002/crossList",
}).then((res) => {
console.log(res);
});
};

2. 在服務(wù)端設(shè)置Access-Control-Allow-Origin
在app2.js中加入
app.all("*", (req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://localhost:3001"); // ++
next();
});

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();
});

到此,我看可以看到跨域請(qǐng)求中加上了cookie。
4. 總結(jié)
1.前端請(qǐng)求時(shí)在request對(duì)象中配置"withCredentials": true;
2.跨域服務(wù)端在response的header中配置"Access-Control-Allow-Origin", “http://xxx:${port}”;
3.跨域服務(wù)端在response的header中配置"Access-Control-Allow-Credentials", “true”
5. 知識(shí)點(diǎn)
1.withCredentials
該XMLHttpRequest.withCredentials屬性是一個(gè)布爾值,指示是否Access-Control應(yīng)使用 cookie、授權(quán)標(biāo)頭或 TLS 客戶端證書等憑據(jù)進(jìn)行跨站點(diǎn)請(qǐng)求。設(shè)置withCredentials對(duì)同站點(diǎn)請(qǐng)求沒有影響。
此外,此標(biāo)志還用于指示何時(shí)在響應(yīng)中忽略 cookie。默認(rèn)值為false. XMLHttpRequest來自不同域的 cookie 不能為自己的域設(shè)置 cookie 值,除非在發(fā)出請(qǐng)求之前withCredentials設(shè)置為。true通過設(shè)置為 true 獲得的第三方 cookiewithCredentials仍將遵循同源策略,因此請(qǐng)求腳本無法通過document.cookie或從響應(yīng)標(biāo)頭訪問。 —來自MDN
2.Access-Control-Allow-Origin
指定了該響應(yīng)的資源是否被允許與給定的origin共享
3.Access-Control-Allow-Credentials
當(dāng)請(qǐng)求的憑證模式 ( ) 為Access-Control-Allow-Credentials時(shí),響應(yīng)標(biāo)頭告訴瀏覽器是否將響應(yīng)暴露給前端 JavaScript 代碼。 Request.credentialsinclude
當(dāng)請(qǐng)求的憑據(jù)模式 ( Request.credentials) 為 時(shí),如果值為include,瀏覽器只會(huì)將響應(yīng)暴露給前端 JavaScript 代碼。 Access-Control-Allow-Credentialstrue
憑據(jù)是 cookie、授權(quán)標(biāo)頭或 TLS 客戶端證書。
當(dāng)用作對(duì)預(yù)檢請(qǐng)求的響應(yīng)的一部分時(shí),這表明是否可以使用憑證發(fā)出實(shí)際請(qǐng)求。請(qǐng)注意,簡單GET 的請(qǐng)求不會(huì)被預(yù)檢。因此,如果對(duì)具有憑據(jù)的資源發(fā)出請(qǐng)求,并且如果此標(biāo)頭未與資源一起返回,則響應(yīng)將被瀏覽器忽略并且不會(huì)返回到 Web 內(nèi)容。
Access-Control-Allow-Credentials頭與 XMLHttpRequest.withCredentials屬性或 Fetch API 構(gòu)造函數(shù)中的credentials選項(xiàng)一起使用。Request()對(duì)于帶有憑據(jù)的 CORS 請(qǐng)求,為了讓瀏覽器向前端 JavaScript 代碼公開響應(yīng),服務(wù)器(使用 Access-Control-Allow-Credentials標(biāo)頭)和客戶端(通過為 XHR、Fetch 或 Ajax 請(qǐng)求設(shè)置憑據(jù)模式)都必須表明它們’正在選擇包括憑據(jù)。 —來自MDN
到此這篇關(guān)于詳解javascript如何在跨域請(qǐng)求中攜帶cookie的文章就介紹到這了,更多相關(guān)javascript跨域攜帶cookie內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript 匿名函數(shù)(anonymous function)與閉包(closure)
JavaScript 匿名函數(shù)(anonymous function)與閉包(closure) ,學(xué)習(xí)js的朋友可以參考下。2011-10-10
JS實(shí)現(xiàn)玩轉(zhuǎn)風(fēng)車
這篇文章主要為大家詳細(xì)介紹了JS實(shí)現(xiàn)玩轉(zhuǎn)風(fēng)車,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02
細(xì)數(shù)JavaScript 一個(gè)等號(hào),兩個(gè)等號(hào),三個(gè)等號(hào)的區(qū)別
下面小編就為大家?guī)硪黄?xì)數(shù)JavaScript 一個(gè)等號(hào),兩個(gè)等號(hào),三個(gè)等號(hào)的區(qū)別。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-10-10
淺談JavaScript中面向?qū)ο蟮牡纳羁截惡蜏\拷貝
下面小編就為大家?guī)硪黄獪\談JavaScript中面向?qū)ο蟮牡纳羁截惡蜏\拷貝。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-08-08
JS實(shí)現(xiàn)的適合做faq或menu滑動(dòng)效果示例
這篇文章主要介紹了JS實(shí)現(xiàn)的適合做faq或menu滑動(dòng)效果,結(jié)合實(shí)例形式分析了基于JS實(shí)現(xiàn)的頁面元素滑動(dòng)漸變效果的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-11-11
前端axios下載excel文件(二進(jìn)制)的處理方法
新接了項(xiàng)目,遇到這樣的需求,通過后端接口下載excel文件,后端沒有文件地址,返回二進(jìn)制流文件。接下來通過實(shí)例代碼給大家分享前端axios下載excel文件(二進(jìn)制)的處理方法,一起看看吧2018-07-07
詳解處理bootstrap4不支持遠(yuǎn)程靜態(tài)框問題
這篇文章主要介紹了詳解處理bootstrap4不支持遠(yuǎn)程靜態(tài)框問題,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-07-07

