使用 Express 检测 NodeJS 上的 AJAX 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15945118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:10:51  来源:igfitidea点击:

Detecting AJAX requests on NodeJS with Express

ajaxnode.jsexpress

提问by michael

I'm using NodeJS with Express. How can I tell the difference between an ordinary browser request and an AJAX request? I know I could check the request headers but does Node/Exprsss expose this information?

我在 Express 中使用 NodeJS。如何区分普通浏览器请求和 AJAX 请求?我知道我可以检查请求头,但是 Node/Exprsss 会公开这些信息吗?

回答by robertklep

Most frameworks set the X-Requested-Withheader to XMLHttpRequest, for which Express has a test:

大多数框架将X-Requested-With标头设置XMLHttpRequest为 ,Express 对此进行了测试:

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

回答by kumarharsh

In case the req.xhris 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...

理想情况下,angular 团队不应该删除它,但实际上应该为 CORS 的飞行前问题找到更好的解决方案,但现在就是这样......