node.js express:如何知道请求是否是 AJAX 请求?

Cra*_*hax 4 ajax node.js express

假设我有一小段代码:

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);
Run Code Online (Sandbox Code Playgroud)

当我进入 app.get(..) 函数时,我想知道发送的 get 请求是否是 AJAX 调用。对象“req”中可以告诉我这个的字段是什么?

lon*_*day 7

标头X-Requested-With: XMLHttpRequestHTTP 标头不会自动添加到 AJAX 请求中,无论是fetch使用该XMLHttpRequest对象还是旧式使用该对象。它通常由 jQuery 等客户端库添加。

如果标头存在,则在 Express 中由 表示request.xhr

如果要将其添加到请求中(此问题的最简单解决方案),您可以将其添加为自定义标头fetch

fetch(url, {
    headers: {
        "X-Requested-With": "XMLHttpRequest"
    }
});
Run Code Online (Sandbox Code Playgroud)

这现在将反映在req.xhr.

更好的解决方案是所设定的Accept标头中的合理值。如果您希望返回 JSON,请设置Acceptapplication/json

fetch(url, {
    headers: {
        "Accept": "application/json"
    }
});
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用以下命令对此进行测试req.accepts

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;
}
Run Code Online (Sandbox Code Playgroud)

这比req.xhr方法强大得多。


Ebr*_*ani 4

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
  }
})
Run Code Online (Sandbox Code Playgroud)