我正在执行以下操作:

......
....
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.use('/public', express.static(__dirname + '/public'));

app.post('/uninstalled', function (req, res, next)
{
  var bodyAsQueryString = queryString.stringify(req.body);
  console.log('bodyAsQueryString = ' + bodyAsQueryString);

  var hmacReceived = req.headers['x-shopify-hmac-sha256'];
  var calculatedHmac = crypto.createHmac('SHA256', config.app.secret);

  req.on("data", function(data)
  {
     console.log('on data...');
     calculatedHmac.update(data);
  });

  req.on("end", function()
  {
     console.log('on end...');
     calculatedHmac = calculatedHmac.digest("base64");
     console.log('hmacReceived = ' + hmacReceived);
     console.log('calculatedHmac = ' + calculatedHmac);
  });

  req.on("error", function(err)
  {
     console.log('on error...');
     console.log(err);
     return next(err);
  });
});


上面的req.on("...")都没有被调用过(控制台记录没有...)-我做错了什么?

bodyAsQueryString的值始终看起来像以下内容(我已经用xxxxx替换了个人数据):


  id = xxxxx&name = xxxxx&email = xxxxxx&domain = xxxxxxx&created_at = 2015-03-21T00%3A31%3A36%2B00%3A00&province =&country = GB&address1 = xxxxxxxxx&zip = E59JY&city = London&source = xxxx&phone = xxxxxx&updated _ %% 3%A3 = 2%2015 = 19-08 3A00&customer_email =&latitude = xxxxx&longitude = -xxxxxx&primary_location_id =&primary_locale = zh-CN&country_code = GB&country_name = United%20Kingdom&currency = USD&timezone =(GMT%2B00%3A00)%20Europe%2FLondon&iana _ %%% ney = own %%% er = 7% 7D&money_with_currency_format =%24%20%7B%7Bamount%7D%7D%20USD&PROVINCE_CODE =&taxes_included =假tax_shipping =&county_taxes =真plan_display_name =联盟&PLAN_NAME =联盟&myshopify_domain = xxxxxx.myshopify.com&google_apps_domain =&google_apps_login_enabled =&money_in_emails_format =%24%7B%7Bamount%7D%7D&money_with_currency_in_emails_format = %24%7B%7Bamount%7D%7D%20USD&eligible_for_payments = false&requires_extra_payments_agreement = false&password_enabled = true&has_storefront = true&setup_required = false

最佳答案

您需要使用原始POST正文而不是req.body。

尝试这样的事情:

app.post('/somepath', function (req, res, next) {
    var hmacReceived = req.headers['x-shopify-hmac-sha256'];
    hmac = crypto.createHmac('SHA256',secret);

    req.on("data", function(data) {
        hmac.update(data);
    });

    req.on("end", function() {
        var calculatedHmac = hmac.digest("base64");
        var test1 = hmacReceived === calculatedHmac;
    });

    req.on("error", function(err) {
        return next(err);
    });
}


此类似问题的更多详细信息:

HMAC MD5 Validation with Node.js, Express and Trialpay

关于node.js - Node.js-即使req.body不为空,也不会调用POST中的req.on(“data”),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32314020/

10-10 14:39