如何使用node.js库form-data制作https帖子?

时间:2015-03-17 13:56:32

标签: node.js https form-data

我们有一个api的客户端需要通过https发布帖子。我们有一个node.js应用程序,并且一直在使用felixge的node-form-data包(https://github.com/felixge/node-form-data)来提交。虽然这些呼叫在客户端测试基于http的api上工作正常,但当我们尝试调用使用https的生产api时,api会响应400,客户端告诉我们这是由于呼叫来了在超过http。

关于我们如何在提交中指定https的任何想法?

我们的代码如下:

var FormData = require('form-data');
    var couponForm = new FormData();
    couponForm.append('data','{"coupon":{"code":"' + couponCode + '", "discount": "' + discountPercentage + '", "type": "percent", "product": "' + productId + '", "times": "1", "expires": "' + couponExpiresDt + '"}}');

couponForm.submit({hostname:config.client_api_host, path:'/api/coupon/add', auth:auth}, function(err, res) {
      res.resume();

      if (err) {
        logger.log('error', 'Client API createDiscount post error:');
        logger.log('error', {err: err});
        callback(err);
      } else if (res.statusCode != 200) {
        logger.log('error', 'Client API createDiscount post response error:');
        console.log('error', res);
        logger.log('error', {statusCode: res.statusCode});
        logger.log('error', {body: res.body});
        callback(new Error('Client API createDiscount post response error:', res.statusCode));
      } else {
        logger.log('info', "Client coupon code " + couponCode +  " has apparently been created");
        callback(null, {coupon_code: couponCode, expires: couponExpiresDt});
      }
    });

1 个答案:

答案 0 :(得分:1)

根据this,您需要在选项中传递protocol: 'https:'

couponForm.submit({
    hostname: config.client_api_host,
    path: '/api/coupon/add',
    auth: auth,
    protocol: 'https:'
}, function(err, res) {
    [...]
});