我的脑袋为此。在Express应用中,我的get请求工作正常。但是,尝试POST结果将传递一个空的req.body。
index.js:
const express = require('express');
const apiRoute = require('./routes/api/index.js');
const bodyParser = require('body-parser');
// const morgan = require('morgan');
const app = express();
app.use(function(req, res, next) {
if (req.headers['content-type'] === 'application/json;') {
req.headers['content-type'] = 'application/json';
}
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/api', apiRoute);
app.listen(3000);
routes / api / index.js
const express = require('express');
const router = express.Router();
const entityRoute = require('./entity');
router.use('/entity', entityRoute);
module.exports = router;
routes / api / entity.js:
const express = require('express');
const router = express.Router();
const db = require('../../database');
router.get('/', function(req, res) {
db.select().from('entity').then(function(data) {
res.send(data);
});
});
router.post('/', function(req, res) {
console.log(req.body);
res.send(req.body);
});
module.exports = router;
我已经经历过无数次了,检查了body-parser文档和其他SO答案,无法解决这个问题。
不确定为什么这种方法无法正常工作...