Steps to make Axios send cookies in its requests automatically
Step 1: In the first step, we will create the new folder by using the below command in the VScode terminal.
mkdir folder-name
cd folder-name
Step 2: After creating the folder, initialize the NPM using the below command. Using this the package.json file will be created.
npm init -y
Step 3: Install all the required dependencies using the below command:
npm install express axios cookie-parser
Step 4: Now create the below Project Structure of our project which includes the file as app.js.
The updated dependencies in package.json file will look like:
"dependencies": {
"axios": "^1.6.2",
"cookie-parser": "^1.4.6",
"express": "^4.18.2"
}
Step 5: Use the below app.js code to make Axios send cookies in its requests automatically.
Example: Write the following code in App.js file.
Javascript
//app.js const axios = require( 'axios' ); const express = require( 'express' ); const cookieParser = require( 'cookie-parser' ); const app = express(); const port = 3000; // using cookie-parser middleware app.use(cookieParser()); app.get( '/make-request' , async (req, res) => { try { // setting cookie on your server res.cookie( 'name1' , 'gfg1' ); res.cookie( 'name2' , 'gfg2' ); // making GET request to an API endpoint const response = await axios.get( 'https://jsonplaceholder.typicode.com/posts/1' , { headers: { Cookie: req.headers.cookie, // passing the client's cookies to the external server }, }); // extracting data from the response const postData = response.data; // sending the data to the client res.json(postData); } catch (error) { // handling errors console.error('Error making Axios request: ', error.message); res.status(500).json({ error: ' Internal Server Error' }); } }); app.listen(port, () => { console.log(`Server is running at http: //localhost:${port}`); }); |
Step to run the application: Run the Server using the following command.
node server.js
Output:
How to make axios send cookies in its requests automatically?
Cookies are small pieces of data stored on the client’s computer for various tasks. If we want to make Axios send cookies in its request automatically, then we can use the ‘withCrendentials‘ options. We need to set it to true in our Axios configuration. This makes sure that cookies are included in both requests and responses. In this article, we will see the practical implementation to automatically make Axios send cookies in its requests.
Contact Us