Express.js - router.METHOD() 方法
router.METHOD() 用于为 Express 提供方法功能,其中 METHOD 表示小写形式的 HTTP 方法之一,例如 GET、POST、PUT 等。因此,实际方法表示如下 -
router.get()
router.post()
router.put() …… 等等
语法
router.METHOD( path, [callback ...], callback )
示例 1
创建一个名为 "routerMETHOD.js" 的文件,复制以下代码片段。创建文件后,使用命令 "node routerMETHOD.js" 运行此代码,如下面的示例所示 -
// router.METHOD() Method Demo Example // Importing the express module const 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 single endpoint router.get('/api', function (req, res, next) { console.log("GET request called for endpoint: %s", req.path); 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 routerMETHOD.js Server listening on PORT 3000 GET request called for endpoint: /api
示例 2
让我们看另一个示例。
// router.METHOD() Method Demo Example // Importing the express module const 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 single endpoint router.get('/api', function (req, res, next) { console.log("%s request called for endpoint: %s", req.method, req.path); res.end(); }); router.post('/api', function (req, res, next) { console.log("%s request called for endpoint: %s", req.method, req.path); res.end(); }); router.delete('/api', function (req, res, next) { console.log("%s request called for endpoint: %s", req.method, req.path); 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 DELETE – localhost:3000/api
输出
C:\home
ode>> node routerMETHOD.js Server listening on PORT 3000 GET request called for endpoint: /api POST request called for endpoint: /api DELETE request called for endpoint: /api
广告