res.links() Method in Express.js


The res.links() method is used for joining two links that are provided as properties of the parameter to populate the response’s Link HTTP header value.

Syntax

res.links( links )

Example 1

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

// res.links(links) 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){
   res.links({
      next: 'https://tutorialspoint.com?page=1',
      middle: 'https://tutorialspoint.com?page=2',
      last: 'https://tutorialspoint.com?page=3'
   });
   console.log(res.get('link'));
});
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 − localhost:3000/api

Output

C:\home
ode>> node resLinks.js Server listening on PORT 3000 <https://tutorialspoint.com?page=1>; rel="next", <https://tutorialspoint.com?page=2>; rel="middle", <https://tutorialspoint.com?page=3>; rel="last"

Example 2

Let's take a look at one more example.

// res.links(links) 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, next){
   res.links({
      next: 'https://tutorialspoint.com?page=1',
      middle: 'https://tutorialspoint.com?page=2',
      last: 'https://tutorialspoint.com?page=3'
   });
   // Using middleware
   next();
})
app.get('/api', function(req, res){
   console.log(res.get('link'));
   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 − localhost:3000/api

Output

C:\home
ode>> node resLinks.js Server listening on PORT 3000 <https://tutorialspoint.com?page=1>; rel="next", <https://tutorialspoint.com?page=2>; rel="middle", <https://tutorialspoint.com?page=3>; rel="last"

Updated on: 29-Jan-2022

336 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements