【问题标题】:node.js express: How can I know if a request is an AJAX request?node.js express:我如何知道请求是否是 AJAX 请求?
【发布时间】:2017-06-16 14:44:24
【问题描述】:

假设我有一小段代码:

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”中可以告诉我的字段是什么?

【问题讨论】:

标签: ajax node.js express


【解决方案1】:

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 方法强大得多。

【讨论】:

    【解决方案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
      }
    })
    

    【讨论】:

    • @lonesomeday 在这种情况下,您必须手动设置标题X-Requested-With: XMLHttpRequest 这将起作用。
    • @SumanKandu 或其他更合适的方法,例如 Accepts 标头。
    【解决方案3】:
    var express = require('express');
    var app = express();
    
    app.get('/', function(req, res){
      var isAjax = req.xhr;
    });
    
    app.listen(3000);
    

    【讨论】:

      猜你喜欢
      • 2014-05-06
      • 2013-05-08
      • 2011-04-21
      • 1970-01-01
      • 2010-12-21
      • 2013-07-13
      • 2012-04-15
      • 2011-11-24
      • 2012-05-08
      相关资源
      最近更新 更多