3

I set app.use(bodyParser.json()); in my app.js (main file). I need to change with bodyParser.text() in another file (foo.js) just for one route. External service send me a request POST 'Content-Type: text/plain; charset=utf-8' and I need to retrieve the content

1

3 Answers 3

6

If you're coming here circa 2021 or later, here is how I set up my app.js file for this issue.

// Import your various routers
const stripeEventsRouter = require('./routes/stripeEvents')
const usersRouter = require('./routes/users')
const commentsRouter = require('./routes/comments')

// use raw parser for stripe events
app.use('/stripeEvents', express.raw({ type: '*/*' }), stripeEventsRouter)

// use express.json parser for all other routes
app.use(express.json())

// set up the rest of the routes
app.use('/users', usersRouter)
app.use('/comments', commentsRouter)
// ...anything else you add below will use json parser
5

See the following API Doc at https://expressjs.com/en/5x/api.html#app.METHOD

You can add middleware(s) to a specific route:

app.get('/', bodyParser.text(), function (req, res) {
  ...
})
4
  • nice! I Must to have a different router? I can do IF inside a same route? Because my route is called from external service
    – JEFF
    Aug 19, 2020 at 13:00
  • Sorry but I'm not following. Can you add an example to the question?
    – Daniel
    Aug 19, 2020 at 13:03
  • external service calls my route /foo. Sometimes use 'application/json' and sometime 'text/plain'. I'd like to use always /foo route.
    – JEFF
    Aug 19, 2020 at 13:10
  • 1
    Yes. See: npmjs.com/package/body-parser#change-accepted-type-for-parsers. You can use both middlewares with use and enforce parser according to the content-type header
    – Daniel
    Aug 19, 2020 at 13:38
0

For express 4XX, you do not need to install body-parser anymore:

router.use('/endpoint', express.text(), itemRoute);

You can read more here: http://expressjs.com/en/api.html#express.text

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.