1

Can someone tell me why this doesn't work:

app.use((req, res, next) => {              
  if (req.originalUrl === '/stripewebhook') {
         next();
   } else {
          bodyParser.json();
          bodyParser.urlencoded({
              extended: true })(req, res, next);

         }
   });

But this works!

app.use((req, res, next) => {          
  if (req.originalUrl === '/stripewebhook') {
         next();
   } else {
          bodyParser.json()(req, res, next);
          bodyParser.urlencoded({
              extended: true });

         }
   });

My original code was just the two bodyParsers middleware:

 ......
    ......
    bodyParser.json();
    bodyParser.urlencoded({
                  extended: true });
    .....

I needed to add the if statement so that the webhook endpoint is skipped but I noticed that I had to set the statements like the above working example...what I am not sure about is if the .urlencoded() ever get executed??

MichaelE
  • 757
  • 14
  • 42

2 Answers2

2

I suspect that the Content Type of the Header may be not matching. You may take a look at this documentation: https://expressjs.com/en/resources/middleware/body-parser.html. and also regarding the implementation: Trying to parse JSON Object from POST Request in Express v4 using body-parser

CyberMessiah
  • 1,084
  • 11
  • 14
1

In node.js, middlewares like bodyParser.json() return functions. If the returned functions are not called, their behaviour does not apply.

The usual way to use them is to give their return values to app.use().

To have a conditional use of a middleware based on the route url, you can do something like:

const express = require('express')
const app = express()
const router = express.Router()
// specific router handling only your conditional middlewares
router.use(bodyParser.json())
router.use(bodyParser.urlencoded({ extended: true }))
// only call this router if the url is not /stripewebhook
app.use(/^(?!\/stripewebhook)/, router)

// [...] all your app-related middlewares

Of course this may not be the solution to your root issue regarding the stripe web hook.

Musinux
  • 31
  • 6
  • Thanks for your explanation above....from my understanding the fact the I am already wrapping the bodyParser in app.use function should take care of the return to the App. ... – MichaelE May 24 '20 at 12:39
  • This is actually my root issue...the If statement took care of the webhook requirement of getting a rawBody...so my concern is what happens when the url is not webhook. – MichaelE May 24 '20 at 12:41
  • My main question was about ensuring that the .urlencoded(..) also get executed...are you saying that router.use() won't get executed until placed in the app.use() function? – MichaelE May 24 '20 at 12:50
  • You should refer to the express documentation about how to use middlewares https://expressjs.com/en/guide/using-middleware.html – Musinux May 24 '20 at 13:04