Express.js – app.post() 方法


app.post() 方法將所有 HTTP POST 請求路由到指定的路徑,並使用指定的回撥函式。

語法

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

引數

  • path − 這是觸發中介軟體函式的路徑。路徑可以是字串、路徑模式、正則表示式或這些內容的陣列。
  • callback − 這些是中介軟體函式或一系列中介軟體函式,它們的作用就像中介軟體,只不過這些回撥可以呼叫 next(路由)。

示例 1

建立一個名為 "appPost.js" 的檔案,然後複製以下程式碼片段。建立檔案後,可以使用命令 "node appPost.js" 來執行此程式碼。

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

// Creating a POST request
app.post('/api', (req, res) => {
   console.log("POST Request Called for /api endpoint")
   res.send("POST Request Called")
})

// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

使用 POST 請求訪問以下端點

https://:3000/api

輸出

C:\home
ode>> node appPost.js Server listening on PORT 3000 POST Request Called for /api endpoint

示例 2

我們來看另一個示例。

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

// Creating a POST request
app.post('/api', (req, res) => {
   console.log("Method called is -- ", req.method)
   res.end()
})

// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

現在,使用 POST 請求訪問以下端點

https://:3000/api

輸出

C:\home
ode>> node appPost.js Server listening on PORT 3000 Method called is -- POST

更新日期: 30-9 月-2021

7K+ 瀏覽次數

開啟您的 職業生涯

完成課程認證

立即開始
廣告
© . All rights reserved.