How can I use body-parser with LoopBack?

前端 未结 8 662
别那么骄傲
别那么骄傲 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:48

    In Loopback ^3.22.0, I can suffice by adding the

    "parse": {
        "body-parser#json": {}
      },
    

    to the server/middleware.json in order to consume application/json post bodies in the server/boot/routes.js

    module.exports = function(app) {
      app.post('/api/sayhello', function(req, res, next) {
         console.log(req.body)
    
    0 讨论(0)
  • 2020-12-24 14:51

    I'm posting this just for informational purposes. I ran into this same issue and found this works as well. You can add a file in the server/boot/ directory with the following:

    var bodyParser = require('body-parser');
    
    module.exports = function(app) {
      app.use(bodyParser.urlencoded({ extended: true }));
    }
    

    Of course, you have to install the package by running:

    npm install --save body-parser
    

    That will save the package under the node_modules directory. If you want it to be the first thing to run, you can start the file name with a "0" since these are loaded in alphabetical order.

    That being said, I figure it is more 'correct' and elegant to use the middleware configuration approach mentioned above than this one, but I share it in the event someone else finds it useful.

    0 讨论(0)
提交回复
热议问题