Wednesday, 6 March 2019

Express: req.accepts(types): Check whether given content types are accepted by client or not


req.accepts(types)
This method is used to check the content types accepted by client. Client set the Accept header with the value that he can able to understand. We can use accepts method to check the types accepted by client.

‘accepts’ method takes one or more content types as input and return the best match that is acceptable by client. If no match found, then it return false.

index.js
const express = require('express')
var cookieParser = require('cookie-parser')

const app = express()

app.use(cookieParser()); 

app.get('/', (req, res) => {
 var responseData = ''
 
 if(req.accepts('html')){
  responseData += 'Client accepts html<br />'
 }
 
 var temp = req.accepts(['json', 'text']);
 if(temp){
  responseData += ('Client accepts ' + temp)
 }

 res.send(responseData)
})

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, you can see below kind of response.



Previous                                                 Next                                                 Home

No comments:

Post a Comment