2017-01-31 6 views
1

のは、私は、コードの小片を持っているとしましょう:node.js express:リクエストがAJAXリクエストであるかどうかをどのように知ることができますか?

var express = require('express'); 
var app = express(); 

app.get('/', function(req, res){ 
    //I want to acccess 'req' and get info whether it's an AJAX call 
}); 

app.listen(3000); 

私はapp.get(..)関数内で行って、私が送信されget要求がAJAX呼び出しであるかどうかを知りたいです。私にこれを伝えることができるオブジェクト 'req'のフィールドは何ですか?

+1

var isAjax = req.xhr; – Omidam81

+0

重複可能性があります。http://stackoverflow.com/questions/18902293/nodejs-validating-request-type-checking-for-json-or-html –

+0

XHRをリクエストするときにパラメータを追加するだけです。 – modernator

答えて

2
app.get('/', function(req, res){ 
    //I want to acccess 'req' and get info whether it's an AJAX call 
    if(req.xhr){ 
    //the request is ajax call 
    } 
}) 
+0

これは 'fetch' APIを使用するときには動作しません。 – lonesomeday

-1
var express = require('express'); 
var app = express(); 

app.get('/', function(req, res){ 
    var isAjax = req.xhr; 
}); 

app.listen(3000); 
1

ヘッダX-Requested-With: XMLHttpRequest HTTPヘッダが自動的fetchまたはXMLHttpRequestオブジェクトの昔ながらの使用のいずれか、AJAX要求に付加されていません。これは、jQueryなどのクライアントライブラリによって追加されることがよくあります。

ヘッダーが存在する場合は、request.xhrで表現されます。

あなたが要求(この問題の最も簡単な解決策)に追加したい場合は、fetchでカスタムヘッダーとして追加することができます

fetch(url, { 
    headers: { 
     "X-Requested-With": "XMLHttpRequest" 
    } 
}); 

これは今req.xhrに反映されます。

さらに良い解決策は、Acceptヘッダーを分かりやすい値に設定することです。あなたはJSONを返すことにしたい場合は、application/jsonAcceptを設定する:あなたは、その後req.acceptsでこれをテストすることができます

fetch(url, { 
    headers: { 
     "Accept": "application/json" 
    } 
}); 

switch (req.accepts(['html', 'json'])) { //possible response types, in order of preference 
    case 'html': 
     // respond with HTML 
     break; 
    case 'json': 
     // respond with JSON 
     break; 
    default: 
     // if the application requested something we can't support 
     res.status(400).send('Bad Request'); 
     return; 
} 

これは、はるかに強力なreq.xhrアプローチを超えています。

関連する問題