How to determine the right Accept Content-Type wit

2019-09-18 12:34发布

问题:

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 - apparently, every call accepts everything!

app.get( '*', function(request, response, next ) {
    console.log('request accepts:')

    if( request.accepts( 'json' ) ){
        console.log( '--> accepts json' )
    }
    if( request.accepts( 'html' ) ){
        console.log( '--> accepts html' )
    }
    if( request.accepts( 'blah' ) ){
        console.log( '--> accepts blah' ) // this does not show up
    }
    if( request.accepts( 'application/json' ) ){
        console.log( '--> accepts json2' )
    }

    next()
} )

If I just visit the page, it accepts json and html.

If I try to use $.getJSON( ... url ... ), it also acccepts json and html.

Headers:

Browser: "Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
Ajax: "Accept application/json, text/javascript, */*; q=0.01"

I'm not an expert about the accepts headers, but it seems that the */* part could be the issue.

How can I determine correct (or perhaps, the first) accept type in ExpressJS? Alternatively: How can I distinguish a JSON request from a normal pagevisit?

回答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



回答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
}