node.js express:我怎么知道请求是否是AJAX请求?
假设我有一小段代码:
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(..)函数时,我想知道发送的请求是否是AJAX调用。 对象'req'中的字段可以告诉我这个字段是什么?
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 } })
头X-Requested-With: XMLHttpRequest
HTTP头不会自动添加到AJAX请求,无论是通过fetch
还是使用旧的XMLHttpRequest
对象。 它通常由客户端库(如jQuery)添加。
如果头部存在,则用request.xhr
表示。
如果你想把它添加到请求(这个问题的最简单的解决scheme),你可以添加它作为自定义标题与fetch
:
fetch(url, { headers: { "X-Requested-With": "XMLHttpRequest" } });
这现在将反映在req.xhr
。
更好的解决scheme是将Accept
头设置为合理的值。 如果您想要返回JSON,请将Accept
设置为application/json
:
fetch(url, { headers: { "Accept": "application/json" } });
然后你可以使用req.accepts
来testing:
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 express = require('express'); var app = express(); app.get('/', function(req, res){ var isAjax = req.xhr; }); app.listen(3000);