Friday 15 March 2019

Express: res.set(field [, value]): Set http response header field


res.set(field [, value])
Sets the response’s HTTP header field to value.
res.set('Content-Type', 'text/plain');

You can even set multiple header fields at once, pass an object as the parameter.
         res.set({
           'Content-Type': 'text/plain',
           'name' : 'demo on response headers'
         })

index.js
'use strict'

const express = require('express')

const app = express()

app.get('/', (req, res) => {
 res.set({
   'Content-Type': 'text/plain',
   'name' : 'demo on response headers'
 })
 
 var contentType = res.get('Content-Type')
 var name = res.get('name')
 
 console.log(`contentType : ${contentType}`)
 console.log(`name : ${name}`)
 
 res.send('Hello World')

})

const port = 3000
app.listen(port, () => console.log(`Application started listening on port ${port}!`))

Run index.js


Open the url ‘http://localhost:3000/’ in browser.


Previous                                                 Next                                                 Home

No comments:

Post a Comment