ヘッダX-Requested-With: XMLHttpRequest
HTTPヘッダが自動的fetch
またはXMLHttpRequest
オブジェクトの昔ながらの使用のいずれか、AJAX要求に付加されていません。これは、jQueryなどのクライアントライブラリによって追加されることがよくあります。
ヘッダーが存在する場合は、request.xhr
で表現されます。
あなたが要求(この問題の最も簡単な解決策)に追加したい場合は、fetch
でカスタムヘッダーとして追加することができます
fetch(url, {
headers: {
"X-Requested-With": "XMLHttpRequest"
}
});
これは今req.xhr
に反映されます。
さらに良い解決策は、Accept
ヘッダーを分かりやすい値に設定することです。あなたはJSONを返すことにしたい場合は、application/json
にAccept
を設定する:あなたは、その後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
アプローチを超えています。
var isAjax = req.xhr; – Omidam81
重複可能性があります。http://stackoverflow.com/questions/18902293/nodejs-validating-request-type-checking-for-json-or-html –
XHRをリクエストするときにパラメータを追加するだけです。 – modernator