简体   繁体   English

使用Express在NodeJS上检测AJAX请求

[英]Detecting AJAX requests on NodeJS with Express

I'm using NodeJS with Express. 我在Express上使用NodeJS。 How can I tell the difference between an ordinary browser request and an AJAX request? 如何分辨普通浏览器请求和AJAX请求之间的区别? I know I could check the request headers but does Node/Exprsss expose this information? 我知道我可以检查请求标头,但是Node / Exprsss是否公开此信息?

Most frameworks set the X-Requested-With header to XMLHttpRequest , for which Express has a test: 大多数框架将X-Requested-With标头设置为XMLHttpRequest ,对此Express进行了测试:

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

In case the req.xhr is not set, say in frameworks such as Angularjs, where it was removed , then you should also check whether the header can accept a JSON response (or XML, or whatever your XHR sends as a response instead of HTML). 万一req.xhr没有设置,例如在框架如Angularjs, 在那里它被删除 ,那么你也应该检查头部是否可以接受一个JSON响应(或XML,或任何你XHR发送的响应,而不是HTML的)。

if (req.xhr || req.headers.accept.indexOf('json') > -1) {
  // send your xhr response here
} else {
  // send your normal response here
}

Of course, you'll have to tweak the second part a little to match your usecase, but this should be a more complete answer. 当然,您必须对第二部分进行一些微调以匹配您的用例,但这应该是一个更完整的答案。

Ideally, the angular team should not have removed it, but should have actually found a better solution for the CORS' pre-flight problem, but that's how it rests now... 理想情况下,角度小组不应该删除它,但实际上应该为CORS的飞行前问题找到更好的解决方案,但这就是现在的情况……

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM