Express.js – req.stale Property


The req.stale property checks whether a request is fresh or stale in the client's cache. If the property returns True, it means the client's cache is stale and all the data needs to be transferred to the client's system. Else, only the non-cached data needs to be transmitted.

Syntax

req.stale

Example 1

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

// req.stale Property Demo Example

// Importing the express
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) {
   console.log(req.stale);
   res.send(req.stale);
});

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 reqStale.js Server listening on PORT 3000 true

Example 2

Let's take a look at one more example.

// req.stale Property Demo Example

// Importing the express
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) {
   if(req.stale) {
      res.json({"status": true});
   } else {
      res.json({"status": false});
   }
});

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 reqStale.js Server listening on PORT 3000 {"status": true}

Updated on: 28-Mar-2022

163 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements