Node.js knowledge - How to set cookie information in HTTP request and response

Node.js knowledge - How to set cookie information in HTTP request and response

[[398674]]

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.

  1. const http = require( 'http' );
  2. function sendRequest() {
  3. const req = http.request({
  4. method: 'GET' ,
  5. host: '127.0.0.1' ,
  6. port: 3010,
  7. path: '/api' ,
  8. headers: {
  9. Cookie: [ 'a=111' , 'b=222' ] // Method 1 setting
  10. }
  11. }, res => {
  12. let data = '' ;
  13. res. on ( 'data' , chunk => data += chunk.toString());
  14. res.on ( 'end' , () => {
  15. console.log( 'response body: ' , data);
  16. console.log( 'response cookie: ' , res.headers[ 'set-cookie' ]);
  17. });
  18. });
  19. req.setHeader( 'Cookie' , [ 'b=222' , 'c=333' ]) // Method 2 setting
  20. req.on ( 'error' , console.error);
  21. req.end ();
  22. }
  23. sendRequest();

The server code is as follows. Note that the response sets the Set-Cookie field.

  1. const http = require( 'http' );
  2.  
  3. http.createServer((req, res) => {
  4. if (req.url === '/api' ) {
  5. console.log( 'received cookie data: ' , req.headers.cookie);
  6. res.setHeader( 'Set-Cookie' , [ 'c=333' , 'd=444' ])
  7. res. end ( 'Cookie set success!' );
  8. } else {
  9. res.end ( 'ok!' );
  10. }
  11. }).listen(3010);

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

>>:  What are the new features of HTTP/2 compared to HTTP/1.1? How to solve head-of-line blocking and header compression?

Recommend

HostDare: 35% off KVM in Los Angeles, starting at $25.99/year

HostDare is a foreign VPS hosting company founded...

5G is eating into Wi-Fi traffic

With the commercialization of 5G and the increase...

What is edge computing in IoT?

The growing number of “connected” devices is gene...

Cloud dedicated line and customer access technology networking solutions

Labs Guide As cloud-network integration becomes i...

Wenku: Improve the IPv6 standard system and develop key standards

On October 11, the 2021 China IPv6 Innovation and...

CloudCone: $14/year KVM-512MB/10GB/3TB/Los Angeles data center

CloudCone has launched a flash sale for 2021, off...

AT&T confirms testing of 400Gbps Ethernet connection

AT&T said it tested 400 Gbps Ethernet (400GbE...