詳解javascript如何在跨域請求中攜帶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">同源請求</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.分別啟動(dòng)兩個(gè)服務(wù)
- node app1.js
- node app2.js
7.項(xiàng)目目錄如下
至此,環(huán)境搭建好了,在瀏覽器訪問http://localhost:3001/index.html即可。
我們把資源部署到了服務(wù)器1上,即端口3001。同源請求的是3001的接口,跨域請求的是3002的接口。
2. 測試同源cookie
加載index.html會(huì)自動(dòng)請求login接口,獲取cookie
點(diǎn)擊同源請求按鈕,發(fā)送同源請求,getUser接口請求會(huì)自動(dòng)攜帶cookie
3. 跨域請求攜帶cookie
點(diǎn)擊跨域請求按鈕
解決:
1.axios請求時(shí)加上 withCredentials: true,再次點(diǎn)擊跨域請求
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(); });
到此,我看可以看到跨域請求中加上了cookie。
4. 總結(jié)
1.前端請求時(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)請求。設(shè)置withCredentials對(duì)同站點(diǎn)請求沒有影響。
此外,此標(biāo)志還用于指示何時(shí)在響應(yīng)中忽略 cookie。默認(rèn)值為false. XMLHttpRequest來自不同域的 cookie 不能為自己的域設(shè)置 cookie 值,除非在發(fā)出請求之前withCredentials設(shè)置為。true通過設(shè)置為 true 獲得的第三方 cookiewithCredentials仍將遵循同源策略,因此請求腳本無法通過document.cookie或從響應(yīng)標(biāo)頭訪問。 —來自MDN
2.Access-Control-Allow-Origin
指定了該響應(yīng)的資源是否被允許與給定的origin共享
3.Access-Control-Allow-Credentials
當(dāng)請求的憑證模式 ( ) 為Access-Control-Allow-Credentials時(shí),響應(yīng)標(biāo)頭告訴瀏覽器是否將響應(yīng)暴露給前端 JavaScript 代碼。 Request.credentialsinclude
當(dā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ù)檢請求的響應(yīng)的一部分時(shí),這表明是否可以使用憑證發(fā)出實(shí)際請求。請注意,簡單GET 的請求不會(huì)被預(yù)檢。因此,如果對(duì)具有憑據(jù)的資源發(fā)出請求,并且如果此標(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 請求,為了讓瀏覽器向前端 JavaScript 代碼公開響應(yīng),服務(wù)器(使用 Access-Control-Allow-Credentials標(biāo)頭)和客戶端(通過為 XHR、Fetch 或 Ajax 請求設(shè)置憑據(jù)模式)都必須表明它們’正在選擇包括憑據(jù)。 —來自MDN
到此這篇關(guān)于詳解javascript如何在跨域請求中攜帶cookie的文章就介紹到這了,更多相關(guān)javascript跨域攜帶cookie內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript 動(dòng)態(tài)生成私有變量訪問器
創(chuàng)建一個(gè)新的用戶對(duì)象,接受一個(gè)有許多屬性的對(duì)象作為參數(shù)2009-12-12TypeScript中Array(數(shù)組)聲明與簡單使用方法
這篇文章主要給大家介紹了關(guān)于TypeScript中Array(數(shù)組)聲明與簡單使用的相關(guān)資料,TypeScript Array(數(shù)組)數(shù)組對(duì)象是使用單獨(dú)的變量名來存儲(chǔ)一系列的值,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12JS實(shí)現(xiàn)鼠標(biāo)滑過鏈接改變網(wǎng)頁背景顏色的方法
這篇文章主要介紹了JS實(shí)現(xiàn)鼠標(biāo)滑過鏈接改變網(wǎng)頁背景顏色的方法,涉及js響應(yīng)鼠標(biāo)事件動(dòng)態(tài)修改頁面元素屬性的實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-10-10微信瀏覽器內(nèi)置JavaScript對(duì)象WeixinJSBridge使用實(shí)例
這篇文章主要介紹了微信瀏覽器內(nèi)置JavaScript對(duì)象WeixinJSBridge使用實(shí)例,本文給出了分享到朋友圈、發(fā)送給好友、分享到騰訊微博、關(guān)注指定的微信號(hào)等功能代碼,需要的朋友可以參考下2015-05-05