Express.js – app.route() 方法
app.route() 方法返回单个路由的实例。该单个路由用于处理带可选中间件的 HTTP 动词。该方法主要用于避免重复名称。
语法
app.route( )
示例 1
创建一个名为 "appRoute.js" 的文件,并复制以下代码段。创建文件后,使用命令 "node appRoute.js" 运行此代码。
// app.route() Demo Example // Importing the express module var express = require('express'); // Initializing the express and port number var app = express(); var PORT = 3000; // Creating a get, post & other requests app.route('/user') .get((req, res, next) => { res.send('GET is called'); console.log('GET is called'); }) .post((req, res, next) => { res.send('POST is called'); console.log('POST is called') }) .all((req, res, next) => { res.send('All others are called'); console.log('All others are called') }) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
点击以下端点/API 访问上述函数 −
输出
C:\home
ode>> node appRoute.js '' '/api' '/api/v1'
示例 2
我们再来看一个示例。
// app.route() Demo Example // Importing the express module var express = require('express'); // Initializing the express and port number var app = express(); var PORT = 3000; // Creating a get, post & other requests app.route('/api/*') .get((req, res, next) => { res.send('GET is called'); console.log('GET is called'); }) .post((req, res, next) => { res.send('POST is called'); console.log('POST is called') }) .all((req, res, next) => { res.send('All others are called'); console.log('All others are called') }) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
对于上述函数,可以在 /api/ 后访问任何端点,它只会通过上述函数。例如,
https://127.0.0.1:3000/api/v1,
.https://127.0.0.1:3000/api/user/path 等
输出
C:\home
ode>> node appRoute.js Server listening on PORT 3000 All others are called GET is called
广告