res.append() Method in Express.js


The res.append() method can append a specified value to the HTTP response header field. It creates new headers with the specified values, if it's not already created. The value string can take both a string input or an array.

Syntax

res.append( field, [value] )

Example 1

Create a file with the name "resAppend.js" and copy the following code snippet. After creating the file, use the command "node resAppend.js" to run this code as shown in the example below −

// res.append(field, [value]) Method Demo Example

// Importing the express module
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 an endpoint
app.get('/api', function(req, res){
   // Appending the localhost URL as link
   res.append('Link', ['',''])
   console.log(res.get('Link')); // URL Array
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   onsole.log("Server listening on PORT", PORT);
});

Hit the following Endpoint with a GET request − http://localhost:3000/api

Output

C:\home
ode>> node resAppend.js Server listening on PORT 3000 [ '', '' ]

Example 2

Let's take a look at one more example.

// res.append(field, [value]) Method Demo Example

// Importing the express module
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 an endpoint
app.get('/api', function(req, res){
   // Setting string value to header
   res.append('Set-Cookie', 'welcome=tutorialsPoint; Path=/;HttpOnly')
   console.log(res.get('Set-Cookie'));
});
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 resAppend.js Server listening on PORT 3000 welcome=tutorialsPoint; Path=/; HttpOnly

Updated on: 29-Jan-2022

922 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements