Search code examples
node.jsexpressmiddlewareloopbackjsbody-parser

How can I use body-parser with LoopBack?


I see that LoopBack has the Express 3.x middleware built-in. Indeed, body-parser is in loopback/node_modules. But I cannot figure out how to use it as middleware. I have never worked with Express 3.x, so maybe it's just that. require does not work, obviously, unless I install body-parser as a dependency in my project.

What should I do in server.js to use body-parser so that web forms are parsed into req.params? That's what it does, right?


Solution

  • After hours of frustration, I just added it to middleware.json like so:

    "parse": {
        "body-parser#json": {},
        "body-parser#urlencoded": {"params": { "extended": true }}
    }
    

    It is installed as a dependency. Now I have form data in req.body in my routes. My server/boot/routes.js looks like this:

    module.exports = function(app) {
        app.post('/mailing_list', function(req, res) {
            console.log(req.body.email);
            res.send({"status": 1, "message": "Successfully added to mailing list."})
        });
    }