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

时间:2017-01-31 08:31:21

标签: 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);

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

3 个答案:

答案 0 :(得分:3)

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

如果标题存在,则表示为Express request.xhr

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

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

现在将反映在req.xhr

更好的解决方案是将Accept标头设置为合理的值。如果您想要返回JSON,请将Accept设置为application/json

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

然后,您可以使用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;
}

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

答案 1 :(得分: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
  }
})

答案 2 :(得分:0)

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

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

app.listen(3000);
相关问题