我使用expressjs创建了一个简单的服务器,并具有post方法,但是对post文章的响应很奇怪,我不知道为什么会发生。有人可以帮我吗? 我期望的是JSON格式。
const express = require('express');
const mongoose = require('mongoose');
const articleModel = require('./models/article');
const bodyParser = require('body-parser');
enter code here
const db = mongoose.connect('mongodb://0.0.0.0:27017/bbs-api');
const app = express();
const port = process.env.PORT || 3000;
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({extended:true}));
// support parsing of application/json type post data
app.use(bodyParser.json());
const bbsRouter = express.Router();
bbsRouter.route('/articles').post( (req, res) => {
console.log(req.body);
// const newArticle = new articleModel(req.body);
// newArticle.save();
// res.status(201).send(newArticle);
res.send(req.body);
});
app.use('/api', bbsRouter);
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log('Example app listening on port 8000!'))
答案 0 :(得分:1)
如果您要发送表单数据(应用程序/ x-www-form-urlencoded),则可以
bbsRouter.route('/articles').post( (req, res) => {
console.log(req.params);
// const newArticle = new articleModel(req.body);
// newArticle.save();
// res.status(201).send(newArticle);
res.send(req.params);
});
答案 1 :(得分:0)
答案 2 :(得分:0)
尝试删除主体解析器,并直接从express中使用中间件并将urlencoded设置为false:
app.use(express.urlencoded({extended:false}));
// support parsing of application/json type post data
app.use(express.json());
请参见here Urlencoded选项文档