Search code examples
sails.jsbody-parser

bodyParser not executing verify option in Sails.js


I'm using body-parser for parsing the data in Sails.js. But is not executing verify option inside bodyParser.json().

Here is my middleware configuration in config/http.js file:

module.exports.http = {
 middleware: {

    order: [
      "cookieParser",
      "session",
      "bodyParser",
      "fileMiddleware",
      "router",
      "www",
      "favicon",
    ],

    bodyParser: (function () {
      const bodyParser = require("body-parser");
      console.log("body-parser executing");
      bodyParser.json({
        limit: "50MB",
        // for verifyingShopifyWebhook
        verify: function(req, res, buf, encoding) {
          console.log("buf", buf); //not getting printed on console
          if (req.url.search("/shopify/webhooks") >= 0) {
              console.log("inside bodyParser verify");
              req.rawbody = buf;
          }
        }
      });
      bodyParser.urlencoded({ limit: "50MB", parameterLimit: 100000, extended:true });
      return bodyParser();
    })(),

    fileMiddleware: (function (){
      const multer = require("multer");
      const upload = multer();
      return upload.fields([{ name: "tagsFile", maxCount: 1 }]);
    })(),
  },
};

I'm getting req.rawbody as undefined when trying to access it in the controller function, and it is not even printing the buf object, so it seems like it is not calling the verify function at all.

Also, as middleware needs to be called on every request, then why App is just printing the body-parser executing at launching time and not on every request call?


Solution

  • OK, so finally I have found the answer after referring to the skipper code.

    Here is what I did with my body-parser middleware:

    bodyParser: (function () {
      const bodyParser = require("body-parser");
      const JSONBodyParser = bodyParser.json({
          limit: "50MB",
          // for verifyingShopifyWebhook
          verify: function(req, res, buf, encoding) {
            if (req.url.search("/shopify/webhooks") >= 0) {
                console.log("inside bodyParser verify");
                req.rawbody = buf;
            }
          }
        });
        const URLEncodedBodyParser = bodyParser.urlencoded({ limit: "50MB", parameterLimit: 100000, extended:true });
    
        return function(req, res, next){
          if(req.is("application/x-www-form-urlencoded")){
            return URLEncodedBodyParser(req, res, next);
          } else {
            return JSONBodyParser(req, res, next);
          }
        }
    })()
    

    So rather than returning the bodyParser(), we need to return the particular parser.

    Here, if the type is x-www-form-urlencoded then it will return URLEncodedBodyParser, otherwise it will return JSONBodyParser.