處理 POST 請求

就像使用 app.get 方法處理 Express 中的 get 請求一樣,你可以使用 app.post 方法來處理髮布請求。

但在你處理 POST 請求之前,你需要使用 body-parser 中介軟體。它簡單地解析了 POSTPUTDELETE 和其他請求的主體。

Body-Parser 中介軟體解析請求的主體並將其轉換為 req.body 中可用的物件

var bodyParser = require('body-parser');

const express = require('express');

const app = express();

// Parses the body for POST, PUT, DELETE, etc.
app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

app.post('/post-data-here', function(req, res, next){

    console.log(req.body); // req.body contains the parsed body of the request.

});

app.listen(8080, 'localhost');