Express是一个小型框架,它位于 Node.js 的 Web 服务器功能之上,以简化其 API 并添加有用的新功能
附加条件:按照以下步骤进行项目设置和模块安装。
步骤 1:使用下面给出的命令创建一个目录。创建目录后,在终端中添加创建目录的位置。
mkdir
第 2 步:现在使用下面给定的命令初始化 npm(节点包管理器)。
npm init
第 3 步:现在在当前目录中安装 Express 并将其保存在依赖项列表中。
npm install express --save
代码实现:
1. app.use(): app.use()函数用于挂载指定的中间件函数(是可以访问请求对象和响应对象的函数,也可以称之为响应-请求循环)在正在指定的路径。当请求路径的基址与路径匹配时,会执行中间件函数。
句法:
app.use([path,],callback[,callback...])
index.js
// Requiring module
const express = require('express')
const app = express()
app.use(function(req, res, next) {
console.log('hello world')
next()
})
app.use(function(req, res, next) {
console.log('happy holidays')
next()
})
// Server setup
var server = app.listen(8080, function () {
var port = server.address().port
console.log("Listening at", port)
})
index.js
// Requiring module
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello Geek');
})
// Server setup
var server = app.listen(8080, function () {
var host = server.address().address
var port = server.address().port
console.log(" Listening : ", port)
})
使用以下命令运行index.js文件:
node index.js
输出:
2. app.get():这个函数告诉服务器在给定路由上获取请求时要做什么。
索引.js
// Requiring module
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello Geek');
})
// Server setup
var server = app.listen(8080, function () {
var host = server.address().address
var port = server.address().port
console.log(" Listening : ", port)
})
使用以下命令运行index.js文件:
node index.js
输出:
app.use() 和 app.get() 方法的区别:
app.use() method |
app.get() method |
It can be used for making routes modular (like exposing a set of routes from an npm module that other web applications could use). | The method is used to expose the GET method. |
It is intended for binding middleware to your application. The path is a mount path and limits the middleware to only apply any paths requested that begin with it. | It is intended for matching and handling a specific route when requested by get http. |
The middleware function is executed when the base of the requested path matches path. | Routes HTTP GET requests to the specified path with the specified callback functions. |
It will allow for all http requests matching that route. | It will only be allowed for http GET requests to that particular route |
Syntax: app.use([path,],callback[,callback…]) | Syntax: app.get(path, callback) |
参考:
- https://www.geeksforgeeks.org/express-js-app-use-function/
- https://www.geeksforgeeks.org/express-js-app-get-function/