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
Asked
Active
Viewed 3,879 times
3

JEFF
- 153
- 2
- 10
-
Does this answer your question? [Express Body Parser with both JSON and binary data passing capability](https://stackoverflow.com/questions/49067596/express-body-parser-with-both-json-and-binary-data-passing-capability) – Jacobi Aug 19 '20 at 12:45
3 Answers
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) {
...
})

Daniel
- 2,288
- 1
- 14
- 22
-
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 '20 at 13:00
-
-
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 '20 at 13:10
-
1Yes. See: https://www.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 '20 at 13:38
5
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

Glenn
- 4,195
- 9
- 33
- 41
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

Omar Dulaimi
- 846
- 10
- 30