尝试使用nodejs同时使用bodyParser和busboy

时间:2015-09-02 21:04:16

标签: node.js express body-parser busboy

我是一个努力学习nodejs的菜鸟 我的应用需要发布,放置和上传文件。 我发现您无法使用BodyParser上传文件。

在我使用BodyParser之前(在应用程序级别添加它),POST和PUT工作。 (当然上传没有)

我找到了这篇文章 [Migrating away from bodyParser() in Express app with busboy?

现在尝试按照文章进行操作。我只是想让POST和PUT工作,然后继续上传。对于PUT和POST我都没有收到错误,但是我的req.body是{}

在我的server.js中我有

mongoose.connection.on("connected", function(ref) {
    console.log("Connected to DB!");

    var app = express();

    port = process.env.port || 3000;
    ip = process.env.ip;

    var router = express.Router();
    router.use(function(req, res, next) {
        next(); 
    });

    app.use('/api', router);

    require('./app/routes')(router);


    app.listen(port, ip, function() {
        console.log('listening on port ' + port);
    });
});

在我的router.js中我(删除了一些混乱)

var ImageModel = require('./models/image.js')
    ,common = require('./common.js')
    ,bodyParser = require('body-parser')
    ,busboy = require('connect-busboy')
; 

module.exports = function(router) {

router.put('/pict/:id',
    bodyParser.urlencoded({ extended: true }),
    function (req, res) {
    console.log("--> %j", req.body);
    ImageModel.findByIdAndUpdate(req.params.id, req.body, function (err, user) {
        if (err) throw err;

        ImageModel.findById(req.params.id, function (err, pict) {
            if (err) res.send(err);
            res.json(pict);
        });

    });
});

router.post('/pict',
    bodyParser.urlencoded({ extended: true }),
    function (req, res) {
    console.log("--> %j", req.body);
    var pict = new ImageModel(req.body);
    pict.save(function (err) {
        if (err) throw err;
        res.json(pict);
    });
});

解决方案

router.put('/pict/:id',
    bodyParser.urlencoded({ extended: true }), bodyParser.json(),
    function (req, res) {
    console.log("--> %j", req.body);
    ImageModel.findByIdAndUpdate(req.params.id, req.body, function (err, user) {
        if (err) throw err;

        ImageModel.findById(req.params.id, function (err, pict) {
            if (err) res.send(err);
            res.json(pict);
        });

    });
});

router.post('/pict',
    bodyParser.urlencoded({ extended: true }), bodyParser.json(),
    function (req, res) {
    console.log("--> %j", req.body);
    var pict = new ImageModel(req.body);
    pict.save(function (err) {
        if (err) throw err;
        res.json(pict);
    });
});

1 个答案:

答案 0 :(得分:0)

问题是我缺少bodyParser.json()。我已使用有效的代码更新了描述