Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

Express.js Cookies


What are cookies

Cookies are small piece of information i.e. sent from a website and stored in user’s web browser when user browses that website. Every time the user loads that website back, the browser sends that stored data back to website or server, to recognize user.

cookie

Install cookie

You have to acquire cookie abilities in Express.js. So, install cookie-parser middleware through npm by using the following command:

expressjs-cookies1

Import cookie-parser into your app.

  1. var express = require(‘express’);
  2. var cookieParser = require(‘cookie-parser’);
  3. var app = express();
  4. app.use(cookieParser());

Define a route:

Cookie-parser parses Cookie header and populate req.cookies with an object keyed by the cookie names.

Let’s define a new route in your express app like set a new cookie:

  1. app.get(‘/cookie’,function(req, res){
  2.      res.cookie(‘cookie_name’ , ‘cookie_value’).send(‘Cookie is set’);
  3. });
  4. app.get(‘/’, function(req, res) {
  5.   console.log(“Cookies :  “, req.cookies);
  6. });

Browser sends back that cookie to the server, every time when it requests that website.


Express.js Cookies Example

File: cookies_example.js

  1. var express = require(‘express’);
  2. var cookieParser = require(‘cookie-parser’);
  3. var app = express();
  4. app.use(cookieParser());
  5. app.get(‘/cookieset’,function(req, res){
  6. res.cookie(‘cookie_name’, ‘cookie_value’);
  7. res.cookie(‘company’, ‘Kreationnext‘);
  8. res.cookie(‘name’, ‘sonoo’);
  9. res.status(200).send(‘Cookie is set’);
  10. });
  11. app.get(‘/cookieget’, function(req, res) {
  12.   res.status(200).send(req.cookies);
  13. });
  14. app.get(‘/’, function (req, res) {
  15.   res.status(200).send(‘Welcome to Kreationnext!’);
  16. });
  17. var server = app.listen(8000, function () {
  18.   var host = server.address().address;
  19.   var port = server.address().port;
  20.   console.log(‘Example app listening at http://%s:%s’, host, port);
  21. });

Output:

Open the page http://127.0.0.1:8000/ on your browser:

expressjs-cookies3

Set cookie:

Now open http://127.0.0.1:8000/cookieset to set the cookie:

expressjs-cookies4

Get cookie:

Now open http://127.0.0.1:8000/cookieget to get the cookie:

expressjs-cookies5

 

Comments

comments