Express.js 中的 router.route() 方法
router.route() 方法返回单一路由的实例,该实例可用于进一步处理 HTTP 动词(带可选中间件)。此方法可用于避免重复的路由命名,因此不会产生类型错误。
语法
router.route( path )
示例 1
创建一个名为"routerRoute.js"的文件并复制以下代码段。创建文件后,使用命令 "node routerRoute.js" 运行此代码,如下例所示 −
// router.route() Method Demo Example // Importing the express module var express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); var PORT = 3000; // Defining a route router.route('/api') .get(function (req, res, next) { console.log("GET request - /api endpoint is called"); res.end(); }); app.use(router); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
使用 GET 请求访问以下端点 − localhost:3000/api
输出
C:\home
ode>> node routerRoute.js Server listening on PORT 3000 GET request - /api endpoint is called
示例 2
我们再看一个示例。
// router.route() Method Demo Example // Importing the express module var express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); var PORT = 3000; // Defining Multiple routings router.route('/api') .get(function (req, res, next) { console.log("/api -> GET request is called"); res.end(); }) .post(function (req, res, next) { console.log("/api -> POST request is called"); res.end(); }) .put(function (req, res, next) { console.log("/api -> PUT request is called"); res.end(); }); app.use(router); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
逐个访问以下端点 −
GET 请求 −localhost:3000/api
POST 请求 −localhost:3000/api
PUT 请求 −localhost:3000/api
输出
C:\home
ode>> node routerRoute.js Server listening on PORT 3000 /api -> GET request is called /api -> POST request is called /api -> PUT request is called
广告