Cookies are simple, small files/data that are sent to client with a
server request and stored on the client side. Every time the user loads
the website back, this cookie is sent with the request. This helps us
keep track of the users actions. There are numerous uses of HTTP
Cookies.
- Session management
- Personalization(Recommendation systems)
- User tracking
npm install --save cookie-parserNow to use cookies with express, we'll require cookie-parser. cookieParser is a middleware which parses cookies attached to the client request object. To use it, we will require it in our index.js file and use it in the same way we use other middleware. We are going to use it on every route. Use the following code to ensure both of these things happen:
var cookieParser = require('cookie-parser'); app.use(cookieParser());cookie-parser parses Cookie header and populates req.cookies with an object keyed by the cookie names. To set a new cookie lets define a new route in your express app like:
var express = require('express'); var app = express(); app.get('/', function(req, res){ res.cookie('name', 'express').send('cookie set'); //Sets name=express }); app.listen(3000);To check if your cookie is set or not, just go to your browser, fire up the console, and enter:
console.log(document.cookie);You will get the output like(you may have more cookies set maybe due to extensions in your browser):
"name=express"The browser also sends back cookies every time is queries the server. To view cookies from your server, on the server console in a route, add the following code to that route:
console.log('Cookies: ', req.cookies);Next time you send a request to this route, you'll get the ouput:
Cookies: { name: 'express' }
Adding cookies with expiration time
You can add cookies that expire. To add a cookie that expires, just pass an object with property 'expire' set to the time when you want it to expire. For example,//Expires after 360000 ms from the time it is set. res.cookie(name, 'value', {expire: 360000 + Date.now()});Another way to set expiration time is using 'maxAge' property. Using this property, we can provide relative time instead of absolute time. An example of this method:
//This cookie also expires after 360000 ms from the time it is set. res.cookie(name, 'value', {maxAge: 360000});
Deleting existing cookies
To delete a cookie, use the clearCookie function. For example, if you need to clear a cookie named foo, use the following code:var express = require('express'); var app = express(); app.get('/clear_cookie_foo', function(req, res){ clearCookie('foo'); res.send('cookie foo cleared'); }); app.listen(3000);Well, that all about cookies in express. We'll use cookies to manage sessions.
No comments:
Post a Comment