
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Req Cookies Property in Express.js
The req.cookies contains the cookies sent by the request while using the cookie-parser middleware. If the cookies are signed, please use the req.signedCookies property.
Syntax
req.cookies
Install the cookie-parser module −
npm install cookie-parser
Example 1
Create a file with the name "reqCookies.js" and copy the following code snippet. After creating the file, use the command "node reqCookies.js" to run this code as shown in the example below −
// req.cookies() Method Demo Example // Importing the express & cookieParser module var cookieParser = require('cookie-parser'); var express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); var PORT = 3000; // Defining the cookieParser to be used app.use(cookieParser()); // Defining an endpoint app.get('/api', function (req, res) { req.cookies.title='TutorialsPoint'; console.log(req.cookies); res.send(); }); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Hit the following Endpoint with a GET request − http://localhost:3000/api
Output
C:\home
ode>> node reqCookies.js Server listening on PORT 3000 [Object: null prototype] { title: 'TutorialsPoint' }
Example 2
Let's take a look at one more example.
// req.cookies() Method Demo Example // Importing the express & cookieParser module var cookieParser = require('cookie-parser'); var express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); var PORT = 3000; // Defining the cookieParser to be used app.use(cookieParser()); // Defining an endpoint app.get('/api', function (req, res) { req.cookies.name='Mayank'; req.cookies.age=21; console.log(req.cookies); res.send(); }); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Hit the following Endpoint with a GET Request − http://localhost:3000/api
Output
C:\home
ode>> node reqCookies.js Server listening on PORT 3000 [Object: null prototype] { title: 'Mayank', age: 21 }
Advertisements