Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Express.js – res.set() Method
The res.set() method can be used for setting the response's HTTP header field to value. You can also set multiple fields at once by passing an object as the parameter.
Syntax
res.set( field, [value] )
Example 1
Create a file with the name "resSet.js" and copy the following code snippet. After creating the file, use the command "node resSet.js" to run this code as shown in the example below −
// res.set(field, [value]) Method 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){
// Setting the response content-type
res.set({
'Content-Type': 'text/html'
});
// Checking if content-type is set
console.log("Content-Type is: ", res.get('Content-Type'));
res.end();
});
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\node>> node resSet.js Server listening on PORT 3000 Content-Type is: text/html; charset=utf-8
Example 2
Let's take a look at one more example.
// res.set(field, [value]) Method 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.use('/api', function(req, res, next){
res.set({
'Content-Type': 'application/zip'
});
next();
})
// Using middleware
app.get('/api', function(req, res){
console.log("Content-Type is : ", res.get('Content-Type'));
res.end();
});
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\node>> node resSet.js Server listening on PORT 3000 Content-Type is : application/zip
Advertisements
