HTTP Cookie[1] is a small piece of data that the server sends to the user's browser and saves locally. The next time the browser makes a request to the same server, it will carry the cookie information to the server. This article comes from "Nodejs Technology Stack" A reader's question, "When Node.js initiates an HTTP request, how to carry cookie information?" Usually when we initiate a request from a browser to a server, the browser will check whether there is a corresponding cookie (there is a cookie folder under the browser's installation directory to store cookie information set under each domain). If there is, it will be automatically added to the cookie field of the Request headers and sent to the server. This is the behavior of the browser, which will automatically help us do it. So what if a Node.js is used as a client? According to the cookie working method defined in RFC 6265[2], during HTTP request processing, the server can set the Set-Cookie field for the client in the Response headers. In addition, the client passes the cookie information to the server in the form of the Cookie field in the Request headers of the HTTP request. Next, we will see how to implement this using the HTTP system module provided by Node.js[3]. This is the client's request method implementation. We can set the Cookie field directly in the headers, or we can call the setHeader() method through the req object returned by http.request.
The server code is as follows. Note that the response sets the Set-Cookie field.
Similarly, when you use HTTP request libraries such as request, node-fetch, etc., their usage is similar. References [1]HTTP Cookie: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Cookies [2]RFC 6265: https://tools.ietf.org/html/rfc6265 [3]HTTP: https://nodejs.org/dist/latest-v14.x/docs/api/http.html This article is reprinted from the WeChat public account "Nodejs Technology Stack", which can be followed through the following QR code. To reprint this article, please contact the Nodejs Technology Stack public account. |
<<: Teach you two tricks to easily export Html pages to PDF files
【Attention】This merchant has run away!!! Limewave...
HostYun has launched a promotion during the Mid-A...
This article takes stock of the smart city applic...
[At the Tianyi Exhibition, China Telecom once aga...
Unesty is a German hosting company founded in 201...
[[398710]] This article is reprinted from the WeC...
CloudServer is a foreign hosting company founded ...
China’s 5G licenses have only been issued for a y...
Recently, the new concept of "high-tech vide...
Recently, US President Trump announced the approv...
[[428404]] This article is reprinted from the WeC...
How to build a simple, stable, reliable and high-...
In this article, we will talk about the wireless ...
With the rapid development of informatization, sw...
We are in the midst of a great digital wave. Inno...