ajax - node.js 表示 : How can I know if a request is an AJAX request?

标签 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”中的字段是什么?

最佳答案

header X-Requested-With: XMLHttpRequest HTTP header 不会自动添加到 AJAX 请求,无论是 fetch或使用 XMLHttpRequest 的老式用法目的。它通常由 jQuery 等客户端库添加。

如果 header 存在,则在 Express 中用 request.xhr 表示.

如果你想将它添加到请求中(这个问题最简单的解决方案)你可以使用 fetch 将它添加为自定义 header 。 :

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

这现在将反射(reflect)在 req.xhr 中.

更好 的解决方案是设置 Accept header 到一个合理的值。如果要返回 JSON,请设置 Acceptapplication/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 强大得多方法。

关于ajax - node.js 表示 : How can I know if a request is an AJAX request?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41952913/

相关文章:

javascript - jquery ajax 多个上传标签

node.js - 在环回应用程序中插入或更新(upsert)

sql - 如何将图像 URL 插入数据库中的表中?

javascript - 原生地从对象中提取属性

javascript - Express 和 angularJs $location.path 不重定向到/

javascript - Angularjs发布请求错误No 'Access-Control-Allow-Origin'

jquery - 使用 .load() 检索参数

javascript - 如何相乘并检查新插入行的字段

ajax - TinyMCE 将光标返回到预先保存的位置——API 4

node.js - Heroku + Socket.io 有时有效有时不行