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
-
Does this answer your question? Express Body Parser with both JSON and binary data passing capability– JacobiAug 19, 2020 at 12:45
3 Answers
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
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) {
...
})
-
nice! I Must to have a different router? I can do IF inside a same route? Because my route is called from external service– JEFFAug 19, 2020 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.– JEFFAug 19, 2020 at 13:10
-
1Yes. 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– DanielAug 19, 2020 at 13:38
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