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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP