如何在特定的快速路线上设置不同的bodyparser

Ahm*_*etK 3 javascript json node.js express

我用的是express 4。

在我的 server.js 中我有express.json() 中间件

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const errorHandler = require('./_helpers/error-handler');



const app = express();

const port = process.env.PORT || 5000;


app.use(cors());
app.use(express.json()); /////////////////////////////////////////


const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, useFindAndModify: true});
const connection = mongoose.connection;
connection.once('open', () => {
    console.log("MongoDB database connection established successfully");
});

// routers
app.use('/api/users', require('./routes/api/users/users.controller'));
app.use('/api/orders', require('./routes/api/orders/orders.controller'));
app.use('/shopify/app', require('./routes/shopify/app/shopify.controller'));
app.use('/shopify/app/webhooks', require('./routes/shopify/app/webhooks/webhooks.controller')); ///////////////

app.use(errorHandler);

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});
Run Code Online (Sandbox Code Playgroud)

但对于'/shopify/app/webhooks'路线,我需要获取原始主体,以便我可以创建哈希,但到目前为止我正在接收对象,因为我有express.json()中间件。

这是我的 webhooks.controller.js 文件

const express = require('express');
const router = express.Router();
const crypto = require('crypto')

const SHOPIFY_API_SECRET_KEY = process.env.SHOPIFY_API_SECRET_KEY;
// router.use(express.raw({ type: "application/json"}));

// routes goes here
router.post('/app/uninstalled', express.raw({ type: 'application/json' }), async (req, res, next) => {
    
    const hmac = req.get('X-Shopify-Hmac-Sha256')
    console.log(req.body);
    // create a hash using the body and our key
    const hash = crypto
        .createHmac('sha256', SHOPIFY_API_SECRET_KEY)
        .update(req.body, 'utf8', 'hex')
        .digest('base64')

    // Compare our hash to Shopify's hash
    if (hash === hmac) {
        // It's a match! All good
        console.log('Phew, it came from Shopifify!')
        res.sendStatus(200)
    } else {
        // No match! This request didn't originate from Shopify
        console.log('Danger! Not from Shopify!')
        res.sendStatus(403)
    }
    
})
Run Code Online (Sandbox Code Playgroud)

我尝试过的是 webhooks.controller.js 中的内容,router.use(express.raw({type: "application/json"})) 我想既然我收到了 json 对象,我可以使用接受 json 的express.raw() 中间件,但它仍然无法正常工作。

jfr*_*d00 5

您必须将此路由放在app.use(express.json())中间件之前,然后您可以将原始中间件直接应用于该路由:

app.use('/shopify/app/webhooks', express.raw({/* put your options here */}), require('./routes/shopify/app/webhooks/webhooks.controller'));
Run Code Online (Sandbox Code Playgroud)

请记住,这行代码实际上必须位于express.json()中间件之前。