邮递员响应正文在使用“表单数据”时为空

时间:2019-02-27 18:12:11

标签: node.js rest postman body-parser

一段时间后,我开始使用新的节点API,突然间,使用Postman'form-data'的数据测试停止了工作。数据以状态码200存储到数据库中,但请求正文(标题和类别)显示为空。我尝试使用原始主体,但效果很好,但还需要使用表单数据在主体中发送文件。

这是我的 app.js 代码段:

app.use(morgan('dev'));
app.use(bodyParser.json());


app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.setHeader(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, application/json, Accept, Authorization'
    );
    if(req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, PATCH');
        return res.status(200).json();
    }
    next();
});

app.use('/articles', articleRoutes);

app.use((req, res, next) => {
    const error = new Error('Not found');
    error.status = 404;
    next(error);
});

型号:

const mongoose = require('mongoose');

const articleSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    title: String,
    category: String,
    date: {type: Date, default: Date.now},
})

module.exports = mongoose.model('article', articleSchema);

Articleroute.js

const express = require('express');
const router = express.Router();

const articleController = require('../controllers/articles');
router.get('/', articleController.article_get_all);
router.post('/', articleController.article_create);
module.exports = router;

article_create

exports.article_create = (req, res, next) => {

    const body = req.body;

    body._id = mongoose.Types.ObjectId();

    const article = new Article(body);
    article
        .save()
        .then(docs => {
            console.log(docs, 'article');
            res.status(200).json(docs);
        })
        .catch(err => {
            console.log(err);
            res.status(500).json({
                error: err
            });
        });
};

我尝试重新安装body-parser模块,但都没有用。

postman screenshot

这是使用表单数据的邮递员结果:

{
    "_id": "5c76d1c01c20fa064cbcbaf1",
    "date": "2019-02-27T18:06:56.287Z",
    "__v": 0
}

0 个答案:

没有答案