Express.js – app.route() 方法
该方法返回单个路由的实例。这个单一的路由可用于处理带有可选中间件的HTTP动词。该方法主要用于避免重名。app.route()
语法
app.route( )
示例1
创建一个名为“appRoute.js”的文件并复制以下代码片段。创建文件后,使用命令“nodeappRoute.js”运行此代码。
//app.route()演示示例
//导入express模块
var express = require('express');
//初始化express和端口号
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调用上述函数-
获取http://localhost:3000/user
POSThttp://localhost:3000/user
PUThttp://localhost:3000/user
输出结果
C:\home\node>> node appRoute.js '' '/api' '/api/v1'
示例2
让我们再看一个例子。
//app.route()演示示例
//导入express模块
var express = require('express');
//初始化express和端口号
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/之后调用任何端点,它只会通过上面的函数传递。例如,
http://localhost:3000/api/,
http://localhost:3000/api/v1,
.http://localhost:3000/api/user/path等
输出结果
C:\home\node>> node appRoute.js Server listening on PORT 3000 All others are called GET is called
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短