在 Express.js 中使用 next() 函数
Express.js是一个强大的工具,用于构建Web服务器以在后端访问API。它有几个使其流行的优点,但它也有一些缺点,例如,需要定义不同的路由或中间件来处理来自客户端的不同传入请求。
在本文中,我们将看到如何next()在Express.js的中间件中使用该功能。Express.js中有很多中间件。我们将使用中间件来定义客户端发出的特定请求的处理程序。app.use()
语法
app.use(path, (req, res, next) )
参数
path-这是将调用中间件的路径。
callback-这是在发生任何错误或调用下一个中间件函数时将调用的回调函数。
示例1
创建一个名为“next.js”的文件并复制以下代码片段。创建文件后,使用命令“nodenext.js”运行此代码。
无next()功能
//next()演示示例
//导入express模块
var express = require('express');
//初始化express和端口号
var app = express();
var PORT = 3000;
//创建中间件
app.use("/", (req, res, next) => {
console.log("Welcome to nhooo");
//这里没有next()函数调用
})
//创建另一个中间件
app.get("/", (req, res, next) => {
console.log("Get Request")
})
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});如果没有该next()函数,您可以看到只调用了第一个函数,而没有调用另一个函数。
输出结果
C:\home\node>> node next.js Server listening on PORT 3000 Welcome to nhooo
示例2
让我们再看一个例子
//next()演示示例
//导入express模块
var express = require('express');
//初始化express和端口号
var app = express();
var PORT = 3000;
//创建中间件
app.use("/", (req, res, next) => {
console.log("Welcome to nhooo");
//在这里调用next()函数
next();
})
//创建另一个中间件
app.get("/", (req, res, next) => {
console.log("Got Request")
})
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});当next()函数被调用时,这两个第一功能和未来功能的调用传递的API端点。
输出结果
C:\home\node>> node next.js Server listening on PORT 3000 Welcome to nhooo Get Request
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短