1

I am a noob trying to learn nodejs My app needs to post, put and upload a file. I have found the you can't upload a file using BodyParser.

Before i was using just BodyParser (adding it at the app level) , the POST and PUT WORKED. ( of course the upload did not )

I found this article [Migrating away from bodyParser() in Express app with busboy?

Now try to follow the article. I am just trying to get the POST and PUT working and then move to upload. for both PUT AND POST I do not get an error but my req.body is {}

in my server.js I have

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);
    });
});

in my router.js i have (remove some clutter)

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);
    });
});

Solution

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);
    });
});
Community
  • 1
  • 1
randy
  • 1,685
  • 3
  • 34
  • 74

1 Answers1

0

The problem was i was missing bodyParser.json(). I have updated the description with the code that worked

randy
  • 1,685
  • 3
  • 34
  • 74