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了。