Express.js router.route()功能
原文:https://www . geesforgeks . org/express-js-router-route-function/
router.route() 函数返回单个路由的实例,然后您可以使用可选的中间件来处理 HTTP 动词。您也可以使用 router.route()函数来避免重复的路由命名和键入错误。
语法:
router.route( path )
参数:路径参数保存指定 URL 的路径。
返回值:返回响应。
快递模块安装:
-
您可以访问安装快速模块的链接。您可以使用此命令安装此软件包。
js npm install express
-
安装快速模块后,您可以使用命令在命令提示符下检查您的快速版本。
js npm version express
-
之后,您可以创建一个文件夹并添加一个文件,例如 index.js。
js node index.js
示例 1: 文件名:index.js
var express = require('express');
var app = express();
var router = express.Router();
var PORT = 3000;
// Single routing
router.route('/user')
.get(function (req, res, next) {
console.log("GET request called");
res.end();
});
app.use(router);
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
运行程序的步骤:
- 项目结构会是这样的:
-
使用以下命令确保您已经安装了 express 模块:
js npm install express
-
Run index.js file using below command:
js node index.js
输出:
```js Server listening on PORT 3000
```
-
现在向 http://localhost:3000/ 发出 GET 请求,您可以在屏幕上看到以下输出:
```js Server listening on PORT 3000 GET request called
```
示例 2: 文件名:index.js
var express = require('express');
var app = express();
var router = express.Router();
var PORT = 3000;
// Multiple routing
router.route('/user')
.get(function (req, res, next) {
console.log("GET request called");
res.end();
})
.post(function (req, res, next) {
console.log("POST request called");
res.end();
})
.put(function (req, res, next) {
console.log("PUT request called");
res.end();
});
app.use(router);
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
使用以下命令运行 index.js 文件:
node index.js
现在向 http://localhost:3000/ 发出 GET、POST、PUT 请求,您可以在屏幕上看到以下输出:
Server listening on PORT 3000
GET request called
POST request called
PUT request called
参考:T2】https://expressjs.com/en/4x/api.html#router.route
版权属于:月萌API www.moonapi.com,转载请注明出处