1. 程式人生 > >Express配置post請求的body解析

Express配置post請求的body解析

const app = express();

app.post('/api/login', (req, res) => {
    console.log(req.body); // undefined

    console.log(req.body['username']); // 報錯
    console.log(req.body['password']); // 報錯
});

預設配置的express伺服器會像這樣找不到request的body,導致拿不到前端推送的內容

解決方案

import * as express from 'express';
import
* as bodyParser from 'body-parser';
const app = express();

// body-parser for POST (see https://github.com/expressjs/body-parser)
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

然後就可以拿到request.body了。