我是 Node JS 的初学者,我正在尝试学习使用 Node.js 和 Express 进行网站开发。我发现了这个词:中间件,特别是当我记录回调函数和
app.use()
函数时。什么是中间件?有何用途? app.use()
函数和中间件有什么联系?
充当操作系统或数据库与应用程序之间桥梁的软件,尤其是在网络上。 谷歌
中间件是位于操作系统和其上运行的应用程序之间的软件。中间件本质上充当隐藏翻译层,支持分布式应用程序的通信和数据管理。 天蓝色
通过遵循定义,如果我们简单地检查工作代码:
// Creating a course
app.post(‘/api/courses’, (request, response) => {
});
// Getting all the courses
app.get(‘/api/courses’, (request, response) => {
});
如果您查看 Express 中称为中间件代码的代码,请使用
request
从服务器请求数据,并使用 response
变量将该数据响应给客户端。这是客户端和服务器之间的桥梁。
在express中,中间件函数是接受请求对象(
req
)、响应对象(res
)和next
函数作为参数的函数。
例如:
// this middleware will run when user hits `https://yourdomain.com/` with GET method
app.get('/',
// middleware
(req, res) => {
res.send('hello world');
}
)
app.use()
静态方法为所有请求执行指定的中间件
例如:
// whenever a user hits a endpoint from your server, this middleware will run first
app.use(
// middleware
(req, res, next) => {
// do someting
next() // pass control to the next middleware
}
)