0

ExpressJS で ajax 呼び出しを他の呼び出しと区別するのに苦労しています。

私が理解している限りrequest.accepts('json')、jsonリクエストを識別するために使用できますか?

問題は、どうやら、すべての呼び出しがすべてを受け入れることです!

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()
} )

ページにアクセスしただけでは、json と html が受け入れられます。

を使用しようとする$.getJSON( ... url ... )と、json と 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"

私は受け入れヘッダーの専門家ではありませんが、その*/*部分が問題になる可能性があるようです。

ExpressJSで正しい(またはおそらく最初の)受け入れタイプを決定するにはどうすればよいですか? あるいは、JSON リクエストと通常のページ訪問を区別するにはどうすればよいですか?

4

2 に答える 2

0

ブラウザによって行われるほとんどすべての GET リクエストは で終了し*/*ます。これは、ほぼすべてを受け入れることを意味します。req.accepted決定を下すために、配列を確認できます。次のようになります。

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

したがって、JSON が存在する場合は特別なリクエストであり、そうでない場合は単純なリクエストです。

于 2016-07-16T16:40:45.620 に答える
-1

の配列を使用して、うまくいくように見える解決策を見つけましたaccepts()

if( request.accepts( [ 'json', 'html' ] ) == 'json' ) {
    // do something
} else {
    // do something else
}
于 2016-07-17T07:47:24.617 に答える