Express.js res.type() Function
Last Updated :
16 Mar, 2023
The res.type() function is used to set the Content-Type HTTP header to the MIME type determined by the mime.lookup() function for the specified type.
Syntax:
res.type( type )
Parameters: The type parameter describes the MIME type.
Return Value: It returns an Object.
Installation of the express module:
1. You can visit the link to Install the express module. You can install this package by using this command.
npm install express
2. After installing the express module, you can check your express version in the command prompt using the command.
npm version express
3. After that, you can just create a folder and add a file, for example, index.js. To run this file you need to run the following command.
node index.js
Example 1: Filename: index.js
javascript
const express = require( 'express' );
const app = express();
const PORT = 3000;
app.get( '/' , function (req, res) {
res.type( '.png' ).send();
console.log(res.get( 'Content-type' ));
});
app.listen(PORT, function (err) {
if (err) console.log(err);
console.log( "Server listening on PORT" , PORT);
});
|
Steps to run the program:
- The project structure will look like this:
1. Make sure you have installed the express module using the following command:
npm install express
2. Run the index.js file using the below command:
node index.js
Output:
Server listening on PORT 3000
Now open the browser and go to http://localhost:3000/, now check your console and you will see the following output:
Server listening on PORT 3000
image/png
Example 2: Filename: index.js
javascript
const express = require( 'express' );
const app = express();
const PORT = 3000;
app.use( '/' , function (req, res, next) {
res.type( '.png' ).send();
next();
})
app.get( '/' , function (req, res) {
console.log( "Content-Type: " ,
res.get( 'Content-type' ));
});
app.listen(PORT, function (err) {
if (err) console.log(err);
console.log( "Server listening on PORT" , PORT);
});
|
Run the index.js file using the below command:
node index.js
Now open the browser and go to http://localhost:3000/, now check your console and you will see the following output:
Server listening on PORT 3000
Content-Type: image/png
Reference: https://expressjs.com/en/5x/api.html#res.type
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...