How can I use body-parser with LoopBack?

前端 未结 8 687
别那么骄傲
别那么骄傲 2020-12-24 13:56

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 middlewar

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-24 14:41

    Based on this answer https://stackoverflow.com/a/29813184/605586 from Ben Carlson you have to

    npm install --save body-parser multer
    

    then in your server.js require the modules:

    var bodyParser = require('body-parser');
    var multer = require('multer');
    

    and use them before app.start:

    app.use(bodyParser.json()); // for parsing application/json
    app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
    app.use(multer().any()); // for parsing multipart/form-data
    

    Then you can create a remote method:

    App.incoming = function (req, cb) {
        console.log(req);
        // the files are available as req.files.
        // the body fields are available in req.body
        cb(null, 'Hey there, ' + req.body.sender);
    }
    App.remoteMethod(
        'incoming',
        {
        accepts: [
            {
            arg: 'req', type: 'object', http: function (ctx) {
                return ctx.req;
            }
            }],
        returns: { arg: 'summary', type: 'string' }
        }
    );
    

    Using this you can upload files and additional data fields to loopback with multipart/form-data.

提交回复
热议问题