自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

面試官 -- 跨域請(qǐng)求如何攜帶 Cookie ?

開(kāi)發(fā) 前端
(常規(guī)的面試套路,一般都會(huì)順著你的回答往深了問(wèn))由于之前的項(xiàng)目都是同源的,不牽涉跨域訪問(wèn),所以一時(shí)沒(méi)有回答出來(lái),后來(lái)研究了下,所以有了這篇文章。

前言

最近在參加面試找工作,陸陸續(xù)續(xù)的面了兩三家。其中面試官問(wèn)到了一個(gè)問(wèn)題:如何解決跨域問(wèn)題?我巴巴拉拉的一頓說(shuō),大概了說(shuō)了四種方法,然后面試官緊接著又問(wèn):那跨域請(qǐng)求怎么攜帶cookie呢?(常規(guī)的面試套路,一般都會(huì)順著你的回答往深了問(wèn))由于之前的項(xiàng)目都是同源的,不牽涉跨域訪問(wèn),所以一時(shí)沒(méi)有回答出來(lái),后來(lái)研究了下,所以有了這篇文章。

閱讀本文,你將學(xué)到:

1.學(xué)會(huì)`withCredentials`屬性;

2.學(xué)會(huì)`axios`配置`withCredentials`;

3.學(xué)會(huì)設(shè)置`Access-Control-Allow-Origin`屬性;

4.學(xué)會(huì)設(shè)置`Access-Control-Allow-Credentials`屬性;

5.學(xué)會(huì)解決跨域請(qǐng)求攜帶源站cookie的問(wèn)題

一. 搭建一個(gè)跨域請(qǐng)求的環(huán)境

思路:

  1.    使用express搭建第一個(gè)服務(wù)A(http://localhost:8000),運(yùn)行在8000端口上;
  2.    A服務(wù)托管index.html(用于在前端頁(yè)面發(fā)送網(wǎng)絡(luò)請(qǐng)求)文件;
  3.    在A服務(wù)中寫(xiě)一個(gè)處理請(qǐng)求的路由,加載index.html頁(yè)面時(shí),種下cookie(這里種cookie為了在請(qǐng)求B服務(wù)時(shí)攜帶上);
  4. 使用express搭建第二個(gè)服務(wù)B(http://localhost:8003),運(yùn)行在8003端口上;
  5. 在A服務(wù)托管的index.html頁(yè)面去請(qǐng)求B服務(wù),然后把cookie傳過(guò)去;

先看下代碼結(jié)構(gòu),相對(duì)比較的簡(jiǎn)單:

A服務(wù)的代碼:

// src/app1.js
const express = require("express");
const app = express();
// `index.html` 加載時(shí)會(huì)請(qǐng)求login接口
// 設(shè)置`cookie`
app.get("/login", (req, res) => {
res.cookie("user", "jay", { maxAge: 2000000, httpOnly: true });
res.json({ code: 0, message: "登錄成功" });
});

// 此接口是檢測(cè)`cookie`是否設(shè)置成功,如果設(shè)置成功的話,瀏覽器會(huì)自動(dòng)攜帶上`cookie`
app.get("/user", (req, res) => {
// req.headers.cookie: user=jay
const user = req.headers.cookie.split("=")[1];
res.json({ code: 0, user });
});

// 托管`index.html`頁(yè)面
// 這樣的話在`index.html`中發(fā)起的請(qǐng)求,默認(rèn)的源就是`http://localhost:8000`
// 然后再去請(qǐng)求`http://localhost:8003`就會(huì)出現(xiàn)跨域了
app.use("/static", express.static("public"));
app.listen("8000", () => {
console.log("app1 running at port 8000");
});

index.html的代碼:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<met
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h2>this is index.html at port 8000</h2>
<button id="button">發(fā)送同源請(qǐng)求</button>
<button id="cross-button">發(fā)送跨域請(qǐng)求</button>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
const button = document.querySelector("#button");
const crossButton = document.querySelector("#cross-button");
axios.get("http://localhost:8000/login", {}).then((res) => {
console.log(res);
});
// 發(fā)送同域請(qǐng)求
button.onclick = function () {
axios.get("http://localhost:8000/user", {}).then((res) => {
console.log(res);
});
};
// 發(fā)送跨域請(qǐng)求
crossButton.onclick = function () {
axios({
method: "get",
url: "http://localhost:8003/anotherService",
}).then((res) => {
console.log(res);
});
};
</script>
</body>
</html>

B服務(wù)的代碼:

// src/app2.js
const express = require("express");
const app = express();
// 定義一個(gè)接口,index.html頁(yè)面請(qǐng)求這個(gè)接口就是跨域(因?yàn)槎丝诓煌?/span>
app.get("/anotherService", (req, res) => {
res.json({ code: 0, msg: "這是8003端口返回的" });
});
app.listen("8003", () => {
console.log("app2 running at port 8003");
});

這個(gè)時(shí)候環(huán)境基本就搭建好了。

二、解決跨域攜帶cookie問(wèn)題

首先我們先在A服務(wù)的index.html頁(yè)面中得到一個(gè)cookie,運(yùn)行A服務(wù):

npm install express -D
node src/app1.js

然后打開(kāi)http://localhost:8000/static/index.html: 沒(méi)有問(wèn)題的話,頁(yè)面長(zhǎng)這樣:

這個(gè)時(shí)候F12打開(kāi)控制臺(tái):可以看到發(fā)送了一個(gè)login請(qǐng)求,并且設(shè)置了cookie,也可以選擇瀏覽器控制臺(tái)的Application頁(yè)簽,選中cookie,可以看到cookie的信息:

然后我們點(diǎn)擊頁(yè)面上的發(fā)送同源請(qǐng)求按鈕,可以看到發(fā)送了一個(gè)user請(qǐng)求,并且已經(jīng)攜帶上了cookie:

接下來(lái)刺激的畫(huà)面來(lái)了,我們點(diǎn)擊 發(fā)送跨域請(qǐng)求 按鈕,出現(xiàn)了跨域請(qǐng)求的報(bào)錯(cuò):

重點(diǎn):接下來(lái)開(kāi)始解決跨域攜帶cookie問(wèn)題:

1. 在前端請(qǐng)求的時(shí)候設(shè)置request對(duì)象的屬性withCredentials為true;

什么是withCredentials?

XMLHttpRequest.withCredentials 屬性是一個(gè)Boolean類(lèi)型,它指示了是否該使用類(lèi)似cookies,authorization headers(頭部授權(quán))或者TLS客戶端證書(shū)這一類(lèi)資格證書(shū)來(lái)創(chuàng)建一個(gè)跨站點(diǎn)訪問(wèn)控制(cross-site Access-Control)請(qǐng)求。在同一個(gè)站點(diǎn)下使用withCredentials屬性是無(wú)效的。

如果在發(fā)送來(lái)自其他域的XMLHttpRequest請(qǐng)求之前,未設(shè)置withCredentials 為true,那么就不能為它自己的域設(shè)置cookie值。而通過(guò)設(shè)置withCredentials 為true獲得的第三方cookies,將會(huì)依舊享受同源策略,因此不能被通過(guò)document.cookie或者從頭部相應(yīng)請(qǐng)求的腳本等訪問(wèn)。

// 修改跨域請(qǐng)求的代碼
crossButton.onclick = function () {
axios({
withCredentials: true, // ++ 新增
method: "get",
url: "http://localhost:8003/anotherService",
}).then((res) => {
console.log(res);
});
};

這個(gè)時(shí)候再去發(fā)送一個(gè)跨域請(qǐng)求,你會(huì)發(fā)現(xiàn)依舊報(bào)錯(cuò),但是我們仔細(xì)看下報(bào)錯(cuò),意思是需要設(shè)置header的Access-Control-Allow-Origin屬性:

2. 在服務(wù)端設(shè)置Access-Control-Allow-Origin

我們修改B(app2.js)服務(wù)的代碼:

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

修改完之后再次發(fā)送一個(gè)跨域請(qǐng)求,你會(huì)發(fā)現(xiàn),又報(bào)錯(cuò)了(接近崩潰),但是跟之前報(bào)的錯(cuò)不一樣了,意思大概就是Access-Control-Allow-Credentials這個(gè)屬性應(yīng)該設(shè)置為true,但是顯示得到的是個(gè)'':

3. 在服務(wù)端設(shè)置Access-Control-Allow-Credentials

再次修改B服務(wù)的代碼(每次修改后需要重新運(yùn)行):

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

再發(fā)送一個(gè)跨域請(qǐng)求:

可以看到,這個(gè)跨域請(qǐng)求已經(jīng)請(qǐng)求成功并且返回?cái)?shù)據(jù)了!而且也攜帶了A服務(wù)的cookie,這個(gè)時(shí)候已經(jīng)大功告成了。

三、總結(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"

如果看完這篇文章能夠幫助到你,請(qǐng)給個(gè)贊哦!

責(zé)任編輯:龐桂玉 來(lái)源: 前端大全
相關(guān)推薦

2022-03-21 07:35:34

處理方式跨域

2022-02-08 08:14:07

Context數(shù)據(jù)線程

2015-08-13 10:29:12

面試面試官

2024-01-10 15:27:58

SessionCookieWeb 應(yīng)用

2024-10-16 15:01:20

2023-02-16 08:10:40

死鎖線程

2011-04-18 14:23:37

javascriptHTML

2022-01-18 09:02:45

請(qǐng)求前端代碼

2021-01-18 05:13:04

TomcatHttp

2021-03-16 22:25:06

作用域鏈作用域JavaScript

2021-03-17 08:39:24

作用域作用域鏈JavaScript

2024-03-18 14:06:00

停機(jī)Spring服務(wù)器

2024-02-20 14:10:55

系統(tǒng)緩存冗余

2023-11-20 10:09:59

2021-07-06 07:08:18

管控數(shù)據(jù)數(shù)倉(cāng)

2024-09-11 22:51:19

線程通訊Object

2024-04-03 00:00:00

Redis集群代碼

2010-08-12 16:28:35

面試官

2025-03-17 00:00:00

2020-06-12 15:50:56

options前端服務(wù)器
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)