How to Set, View and Manipulate Cookies using ‘Response.cookie()’ and Postman ?
Last Updated :
05 Jan, 2024
Cookies enable websites to store small pieces of information on a user’s device. It helps enhance user experience and enable various functionalities. In this article, we’ll explore a simple way to manipulate cookies using the ‘Response.cookie()’ function
Prerequisite:
The ‘Response.cookie()‘ function is like a tool for developers to handle cookies in what they send back to a user’s browser. With it, they can control stuff like the cookie’s name, the value when it expires, and how secure it is.
Syntax:
app.get('/set-cookie', (req, res) => {
res.cookie('username', 'JohnDoe', { maxAge: 900000, httpOnly: true });
res.send('Cookie has been set!');
});
In the above syntax, when a user accesses the ‘/set-cookie’ route, the server responds by setting a cookie named ‘username’ with the value ‘JohnDoe.’
Steps to set and view cookie:
Step 1: Initiallized an Express application and install the required dependencies.
npm init -y
npm i express cookie-parser
Folder Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"cookie-parser": "^1.4.6",
"express": "^4.18.2"
}
Example: Create a server.js file and write the following code.
Javascript
const express = require( "express" );
const cookieParser = require( "cookie-parser" );
const app = express();
app.use(cookieParser());
app.get( "/set-cookie" , (req, res) => {
res.cookie( "username" , "JohnDoe" , { maxAge: 900000, httpOnly: true });
res.send( "Cookie has been set!" );
});
app.get( "/view-cookies" , (req, res) => {
res.send(`Cookies: ${JSON.stringify(req.cookies)}`);
});
app.listen(3000, () => {
console.log( "Server is running on port 3000" );
});
|
Use below command to run “server.js”.
node server.js
Testing Route using Postman:
Step 1: Enter the url in the postman ,”http://localhost:3000/set-cookie”. This will set the cookie username and value as “JhonDoe”.
Step 2: Hit the url “http://localhost:3000/view-cookies“. You will get the cookie value which was set in above step.
Response Process:
All steps to set cookie
Conclusion:
By following above article, you can set cookie data that can be sent to browser. The cookies data cannot be accessed by client side browser script. In this article,you learned how to set or manuplate cookie and view the cookie in response.
Share your thoughts in the comments
Please Login to comment...