Express.js – 在方法中使用 app.METHOD()


app.METHOD() 用於對映或路由 HTTP 請求,其中的 METHOD 表示該請求的 HTTP 方法,例如 GET、POST、PUT 等,但為小寫形式。因此,這些方法是 app.get()、app.post()、app.get() 等。

語法

app.METHOD(path, callback, [callback])

引數

  • path − 這是呼叫中介軟體函式的路徑。路徑可以是字串、路徑模式、正則表示式或所有這些項的陣列。

  • callback − 這是中介軟體函式或一系列中介軟體函式,除了這些回撥可以呼叫後面(路由)之外,這些函式的作用就像中介軟體。

示例 1

建立一個檔案 "appMethod.js" 並複製以下程式碼片段。建立檔案後,使用命令 "node appMethod.js" 執行此程式碼。

// app.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;

// This api will handle the GET request
app.get('/api', function(req, res){
   res.send("GET method called");
});

// This api will handle the POST request
app.post('/api', function(req, res){
   res.send("POST method called");
});

// This api will handle the PUT request
app.put('/api', function(req, res){
   res.send("PUT method called");
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

訪問以下端點以獲取響應

輸出

C:\home
ode>> node appMethod.js Server listening on PORT 3000

在瀏覽器中,您將看到以下輸出

更新日期:2021-10-01

378 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.