当前位置:网站首页>How to carry cookies in cross domain requests?
How to carry cookies in cross domain requests?
2022-04-21 11:29:00 【Front end talent】

Preface
I've been interviewing for a job recently , We met two or three companies one after another . The interviewer asked a question : How to solve cross domain problems ? I Babalala's meal said , About four methods are mentioned , Then the interviewer asked : How to carry cross domain requests cookie Well ?( The usual interview routine , Usually follow your answer and ask deeply ) Because previous projects are homologous , Cross domain access is not involved , So I didn't answer for the moment , Later, I studied , So with this article .
Read this article , You will learn :
1. Learn to `withCredentials` attribute ;
2. Learn to `axios` To configure `withCredentials`;
3. Learn to set `Access-Control-Allow-Origin` attribute ;
4. Learn to set `Access-Control-Allow-Credentials` attribute ;
5. Learn to solve cross domain requests and carry the origin cookie The problem of ;
One . Build a cross domain request environment
Ideas :
Use
expressBuild the first serviceA(http://localhost:8000), Running on the8000On port ;AService hostingindex.html( Used to send network requests on the front page ) file ;stay
AWrite a route for processing requests in the service , loadindex.htmlWhen the page is , plantcookie( Here kindcookieIn order to requestBBring... When serving );Use
expressBuild a second serviceB(http://localhost:8003), Running on the8003On port ;stay
AService hostedindex.htmlPage to requestBservice , And then putcookieTransfer the past ;
Let's look at the code structure first , Relatively simple :
A The code for the service :
// src/app1.js
const express = require("express");
const app = express();
// `index.html` Request when loading login Interface
// Set up `cookie`
app.get("/login", (req, res) => {
res.cookie("user", "jay", { maxAge: 2000000, httpOnly: true });
res.json({ code: 0, message: " Login successful " });
});
// This interface is used to detect `cookie` Whether the setting is successful , If the setting is successful , The browser will automatically carry `cookie`
app.get("/user", (req, res) => {
// req.headers.cookie: user=jay
const user = req.headers.cookie.split("=")[1];
res.json({ code: 0, user });
});
// trusteeship `index.html` page
// Such words are in `index.html` Request from , The default source is `http://localhost:8000`
// Then ask `http://localhost:8003` There will be cross domain
app.use("/static", express.static("public"));
app.listen("8000", () => {
console.log("app1 running at port 8000");
});
index.html Code for :
<!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>
</head>
<body>
<h2>this is index.html at port 8000</h2>
<button id="button"> Send homology request </button>
<button id="cross-button"> Send a cross-domain request </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);
});
// Send the same domain request
button.onclick = function () {
axios.get("http://localhost:8000/user", {}).then((res) => {
console.log(res);
});
};
// Send a cross-domain request
crossButton.onclick = function () {
axios({
method: "get",
url: "http://localhost:8003/anotherService",
}).then((res) => {
console.log(res);
});
};
</script>
</body>
</html>
B The code for the service :
// src/app2.js
const express = require("express");
const app = express();
// Define an interface ,index.html The interface of page request is cross domain ( Because the ports are different )
app.get("/anotherService", (req, res) => {
res.json({ code: 0, msg: " This is a 8003 Port returned " });
});
app.listen("8003", () => {
console.log("app2 running at port 8003");
});
At this time, the environment is basically set up .
Two 、 Solve cross domain portability cookie problem
First of all, we are in A Service index.html Get a... In the page cookie, function A service :
npm install express -D
node src/app1.js
Then open the http://localhost:8000/static/index.html: If there is no problem , Page length :
This is the time F12 Open console : You can see that a login request , And set up cookie, You can also choose the... Of the browser console Application Tab , Choose cookie, You can see cookie Information about :
Then we click... On the page Send homology request Button , You can see that a user request , And have carried cookie:
Here comes the exciting picture , We click Send a cross-domain request Button , An error occurred in the cross domain request :
a key : Next, we begin to solve the problem of cross domain portability cookie problem :
1. Set when the front end requests request Object properties withCredentials by true;
What is? withCredentials?
XMLHttpRequest.withCredentials Property is a Boolean type , It indicates whether to use something like cookies,authorization headers( Head Authorization ) perhaps TLS Client certificate is a kind of qualification certificate to create a cross site access control (cross-site Access-Control) request . Use... Under the same site withCredentials Property is invalid .
If you are sending XMLHttpRequest Request before , Not set withCredentials by true, Then you can't set... For its own domain cookie value . And by setting up withCredentials by true Third party acquisition cookies, Will still enjoy the same source strategy , Therefore, it cannot be passed document.cookie Or access... From the script corresponding to the request in the header .
// Modify the code of cross domain request
crossButton.onclick = function () {
axios({
withCredentials: true, // ++ newly added
method: "get",
url: "http://localhost:8003/anotherService",
}).then((res) => {
console.log(res);
});
};
At this time, send a cross domain request , You will find that you still report an error , But let's take a closer look at the error report , It means you need to set header Of Access-Control-Allow-Origin attribute :
2. Set... On the server Access-Control-Allow-Origin
We modify B(app2.js) The code for the service :
// Add... Before all routes , All requests can be blocked
app.all("*", (req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://localhost:8000");
next();
});
After modification, send a cross domain request again , You'll find that , Wrong again. ( Close to collapse ), But it's different from the mistake reported before , That's about it Access-Control-Allow-Credentials This property should be set to true, But what it shows is '':
3. Set... On the server Access-Control-Allow-Credentials
Revise again B The code for the service ( You need to run again after each modification ):
// Add... Before all routes , All requests can be blocked
app.all("*", (req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://localhost:8000");
res.header("Access-Control-Allow-Credentials", "true"); // ++ newly added
next();
});
Send another cross domain request :
You can see , The cross domain request has succeeded and returned data ! And also carry A Service cookie, It's done by this time .
3、 ... and 、 summary
When the front-end requests, it is in
requestObject"withCredentials": true;The service side in
responseOfheaderMiddle configuration"Access-Control-Allow-Origin", "http://xxx:${port}";The service side in
responseOfheaderMiddle configuration"Access-Control-Allow-Credentials", "true"
If reading this article can help you , Please give me a compliment ~
author :Ethan01
https://juejin.cn/post/7066420545327218725
版权声明
本文为[Front end talent]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204211123548584.html
边栏推荐
- AD中如何在3D下生成PCB实时快照
- How does IOT platform realize business configuration center
- IoT平台如何实现业务配置中心
- 3年产品经理,从5k到30k,我是这样成长的(上)
- Cycle de vie des paquets dans kubernets - partie 1
- Suffix array application
- 54000 stars all return to zero. Project Author: I regret it very much
- 微信小程序转uniapp
- 打开应用出现 “需要使用新应用一打开此ms-gamingoverlay链接”
- 文件传输(上传下载)
猜你喜欢

Leetcode buckle plug-in settings of idea

【招聘测评题】中的(行测)图形推理题基本逻辑总结(附例题)

塔米狗资讯|国资委发言:支持上市公司采用企业并购融资手段拓展主业

塔米狗项目解读|海南奥特莱斯旅业开发有限公司100%股权转让

Huisheng Huiying 2022 releases 8 new features of Huisheng Huiying 2022 (official)

星汉未来云原生基础治理平台SchedulX V1.1.0 重磅发布,助力企业降本增效

塔米狗知识|股权转让合法程序有哪些?

Suffix array application

【优质原创】分享几个Sklearn模块中不为人知又超级好用的API函数

Filter
随机推荐
中天钢铁18个产品捧“金杯”
Leetcode1615. 最大网络秩(medium,图论基础)
JSON及相关
Realize browser multi tab communication
package. json
Review suffix array & automata
El expression
[binary number] symmetric binary tree
MQ related processes and contents
MQ相關流程及各項內容
数据清洗 Chapter05 | 数据分组与数据不平衡
From station B and little red book, how to do a good job of community products?
数字藏品平台开发,数字藏品app搭建
I need to write two interfaces to receive data, and then store the data in the database to complete data persistence
为什么各大APP都推出了适老版?
Suffix array special training
5.4万Star全部归零,项目作者:十分后悔
把数组字典写入csv格式
注册新西兰公司流程和需要的资料
JSTL -- JSP 标准标签库