Friday, 15 March 2019

Express: res.format(object): perform content negotiation on Accept http header


res.format(object)
It performs the content negotiation on the request ‘Accept’ header.

app.get('/', (req, res) => {
         res.format({
           'text/plain': function(){
                  res.send('Hello World')
           },

           'text/html': function(){
                  res.send('<h1>Hello World</h1>')
           },

           'application/json': function(){
                  res.send({ message: 'Hello World' })
           },

           'default': function() {
                  res.status(406).send('Not Acceptable format')
           }
         })
})

As you see above snippet,
a.   If Accept header set to ‘text/plain’, then Hello World message is returned
b.   If Accept header set to ‘text/html’, then '<h1>Hello World</h1>' message is returned.
c.    If Accept header set to  'application/json', then { message: 'Hello World' } message is returned.
d.   If Accept header is not matches any of the above, then status code 406 is sent to the client.

index.js
'use strict'

const express = require('express')

const app = express()

app.get('/', (req, res) => {
 res.format({
   'text/plain': function(){
  res.send('Hello World')
   },

   'text/html': function(){
  res.send('<h1>Hello World</h1>')
   },

   'application/json': function(){
  res.send({ message: 'Hello World' })
   },

   'default': function() {
  res.status(406).send('Not Acceptable format')
   }
 })
})

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

Run index.js

Use any rest client like Postman and hit below requests.

Method: GET
URL: http://localhost:3000
Request Headers:

Accept : text/plain



Method: GET
URL: http://localhost:3000
Request Headers:
Accept : text/html



Method: GET
URL: http://localhost:3000
Request Headers:
Accept : application/json


Previous                                                 Next                                                 Home

No comments:

Post a Comment