简体   繁体   中英

NodeJS set / add cookies

I need simple Node JS server which returns some html page and set one or more cookies to it.

How should I add one or more cookies in Node JS?

For example you have directory and 2 files inside:

my_folder:

  • main.js
  • index.html

Steps:

  1. Install cookie: npm install cookie
  2. main.js should be next:

 var http = require('http'), fs = require('fs'), cookie = require('cookie'); http.createServer(function (request, response) { var setCookies = []; setCookies.push( cookie.serialize('name1', 'Jhon1') ); setCookies.push( cookie.serialize('name2', 'Jhon2') ); response.setHeader('Set-Cookie', setCookies); response.writeHead(200, { 'Content-Type': 'text/html' }); fs.createReadStream('./index.html').pipe(response); }).listen(8000); console.log('Server is started: "http://localhost:8000"'); 

  1. Run: $ node ./main.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM