Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get and Set a Single Cookie with Node.js HTTP Server

I want to be able to set a single cookie, and read that single cookie with each request made to the nodejs server instance. Can it be done in a few lines of code, without the need to pull in a third party lib?

var http = require('http');  http.createServer(function (request, response) {   response.writeHead(200, {'Content-Type': 'text/plain'});   response.end('Hello World\n'); }).listen(8124);  console.log('Server running at http://127.0.0.1:8124/'); 

Just trying to take the above code directly from nodejs.org, and work a cookie into it.

like image 369
Corey Hart Avatar asked Aug 03 '10 05:08

Corey Hart


People also ask

How do I request a cookie in node JS?

createServer(function (request, response) { // To Read a Cookie const cookies = parseCookies(request); // To Write a Cookie response. writeHead(200, { "Set-Cookie": `mycookie=test`, "Content-Type": `text/plain` }); response. end(`Hello World\n`); }). listen(8124); const {address, port} = server.

How do I set-cookie in HTTP request?

The Set-Cookie header is sent by the server in response to an HTTP request, which is used to create a cookie on the user's system. The Cookie header is included by the client application with an HTTP request sent to a server, if there is a cookie that has a matching domain and path.

Can cookie be set on a server?

A regular cookie can be set server side or client side. The 'classic' cookie will be sent back with each request. A cookie that is set by the server, will be sent to the client in a response. The server only sends the cookie when it is explicitly set or changed, while the client sends the cookie on each request.


1 Answers

There is no quick function access to getting/setting cookies, so I came up with the following hack:

const http = require('http');  function parseCookies (request) {     const list = {};     const cookieHeader = request.headers?.cookie;     if (!cookieHeader) return list;      cookieHeader.split(`;`).forEach(function(cookie) {         let [ name, ...rest] = cookie.split(`=`);         name = name?.trim();         if (!name) return;         const value = rest.join(`=`).trim();         if (!value) return;         list[name] = decodeURIComponent(value);     });      return list; }  const server = http.createServer(function (request, response) {     // To Read a Cookie     const cookies = parseCookies(request);      // To Write a Cookie     response.writeHead(200, {         "Set-Cookie": `mycookie=test`,         "Content-Type": `text/plain`     });      response.end(`Hello World\n`); }).listen(8124);  const {address, port} = server.address(); console.log(`Server running at http://${address}:${port}`); 

This will store all cookies into the cookies object, and you need to set cookies when you write the head.

like image 71
Corey Hart Avatar answered Oct 14 '22 02:10

Corey Hart