Express.js – req.xhr 属性


req.xhr 属性是一个布尔属性,当请求的X-Requested-With 头字段是"XMLHttpRequest" 时,返回 True。True 指针基本上表示该请求是由客户端库(例如 jQuery)发出的。

语法

req.xhr

示例 1

"reqXhr.js" 为名称创建一个文件,然后复制以下代码段。创建文件后,使用命令"node reqXhr.js" 来运行该代码,如下面的示例所示 −

// req.xhr Property Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint
app.get('/api', function (req, res) {
   console.log("Xhr is: ", req.xhr);
   res.send(req.xhr);
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

使用GET 请求访问以下端点 − localhost:3000/api

输出

C:\home
ode>> node reqXhr.js Server listening on PORT 3000 Xhr is: false

示例 2

我们来看另一个示例。

// req.xhr Property Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint
app.get('/api', function (req, res) {
   console.log("Xhr is: ", req.xhr);
   res.send(req.xhr);
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

使用GET 请求访问以下端点 −

https://:3000/api

并设置以下头文件 −

X-Requested-With = XMLHttpRequest

输出

C:\home
ode>> node reqXhr.js Server listening on PORT 3000 Xhr is: true

更新于: 28-03-2022

浏览量 472

开启您的 职业

完成课程来认证

开始
广告
© . All rights reserved.