Skip to content Skip to sidebar Skip to footer

How To Determine The Right Accept Content-type With Expressjs

I'm having trouble to distinguish an ajax call from other calls in ExpressJS. As far as I understand, I can use request.accepts('json') to identify a json request? The problem is -

Solution 1:

Almost all GET requests made by the browser are finished with */*, it means that it accepts pretty much everything. In order to make a decision, you could check req.accepted array. It looks like this:

[ { value: 'application/json',
    quality: 1,
    type: 'application',
    subtype: 'json' },
{ value: 'text/html',
     quality: 0.5,
     type: 'text',
     subtype: 'html' } ]

Thereby, if JSON is present it is a special request, otherwise it is a simple request

Solution 2:

I've found a solution that seems to work, by using an array for accepts():

if( request.accepts( [ 'json', 'html' ] ) == 'json' ) {
    //do something
} else {
    //do something else
}

Post a Comment for "How To Determine The Right Accept Content-type With Expressjs"