Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what is the purpose of express res.get(field) method?

I saw some code examples about using express res.get(field)

Is it for debugging purpose or there are other use cases for it?

the code examples I saw looks like this :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var express = require('express');
var app = express();
var PORT = 3000;

// Defining an endpoint
app.get('/api', function(req, res){

   // Setting the Content-type
   res.set({
      'Content-Type': 'application/json',
   });

   // "text/plain"
   console.log(res.get('Content-Type'));
   res.end();
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

when hitting the end point the output :

application/json; charset=utf-8

>Solution :

Express uses this method internally to check if particular headers are set, typically to set a default if they aren’t or to augment them (for instance, in your example you set the Content-Type header to application/json, and Express appended ; charset=utf-8 to it).

You could imagine situations where a request handler wants to see if a particular middleware (perhaps a third-party one) set a particular header and/or a particular value, and adjust the way it handles the final response.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading