Nodejs中的一个路由使用bodyParser.raw

4

我在我的index.js文件中有以下内容:

app.use(bodyParser.json());

但 Stripe Webhooks 要求如下:

将原始内容匹配为应用程序/json 格式

如果我将 index.js 更改为以下内容:

app.use(bodyParser.raw({type: 'application/json'}));

这是可行的。但是我所有其他的API路由将不再起作用。以下是我的路由:

router.route('/stripe-events')
  .post(odoraCtrl.stripeEvents)

如何仅在此API路由中改变原始请求体?

4个回答

11
你可以通过以下方法同时访问两个内容:
app.use(bodyParser.json({
  verify: (req, res, buf) => {
    req.rawBody = buf
  }
}))

现在原始数据可通过 req.rawBody 获得,JSON解析后的数据可通过 req.body 获得。


1
将它们分成两个路由器'/api'和'/stripe-events',并仅为第一个路由器指定bodyParser.json()

stripeEvents.js

const express = require('express')
const router = express.Router()
...
router.route('/stripe-events')
  .post(odoraCtrl.stripeEvents)
module.exports = router

api.js

const express = require('express')
const router = express.Router()
...
router.route('/resource1')
  .post(addResource1)
router.route('/resource2')
  .post(addResource2)
module.exports = router

const stripeEventsRouter = require('./routers/stripeEvents';
const apiRouter = require('./routers/api';

apiRouter.use(bodyParser.json());
stripeEventsRouter.use(bodyParser.raw({type: 'application/json'}));
app.use('/api', stripeEventsRouter);
app.use('/api', apiRouter);

apiRouterstripeEventsRouter是什么意思?你能举个例子吗? - Vahid Najafi
我在我的回答中添加了示例。 - Anatoly

1

bodyParser.raw() 返回一个中间件函数。不要将其传递给app.use(),而是像添加其他自定义中间件一样,在单个路由的路由处理程序函数之前将返回值作为输入参数添加。

const matchRawBodyToJSON = bodyParser.raw({type: 'application/json'});

router.route( '/stripe-events' )
  .post( matchRawBodyToJSON, odoraCtrl.stripeEvents )

0
同样的需求在这里,我的解决方案是:对于每个普通的API使用路由器,并使用不同的配置使用单独的单个POST处理程序。
const express = require('express');
const bodyParser = require("body-parser");

const baseRouter= express.Router();
baseRouter.route('/your_api_route').get(your_function);
baseRouter.route('/your_api_route2').post(your_function2);
baseRouter.use(bodyParser.urlencoded({ extended: true }));
baseRouter.use(bodyParser.json());

const app = express();
app.use("/", baseRouter)
.post('/webhook', express.raw({type: 'application/json'}),webhook) //this is a special route for stripe webhook (in my case)
+.listen(...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接