为一条快速路线设置特定的 bodyParser

JEF*_*EFF 3 node.js express

app.use(bodyParser.json());我在 app.js (主文件)中设置。我需要在另一个文件(foo.js)中更改bodyParser.text()一条路线。外部服务向我发送请求 POST 'Content-Type: text/plain; charset=utf-8',我需要检索内容

Gle*_*enn 7

如果您在 2021 年左右或之后来到这里,以下是我针对此问题设置app.js文件的方法。

// 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
Run Code Online (Sandbox Code Playgroud)


Dan*_*iel 5

请参阅以下 API 文档:https://expressjs.com/en/5x/api.html#app.METHOD

您可以将中间件添加到特定路由:

app.get('/', bodyParser.text(), function (req, res) {
  ...
})
Run Code Online (Sandbox Code Playgroud)