类型'form-data / multipart'的HTTPS请求(使用https nodejs模块)不起作用

时间:2018-11-11 13:10:43

标签: javascript node.js https multipartform-data

我有以下卷曲请求,该卷曲请求按预期工作正常:

  

curl-用户'api:MY_API_KEY'   https://api.mailgun.net/v3/mydomain/messages --form from ='我的名字   '--form to=validaddress@domain.com --form   subject =“你好3!” --form text ='正在测试发送电子邮件!'

但是我需要使用标准https模块形式的nodejs将这个请求设计为有效的https请求,并且尝试了以下代码,但是我不断收到400(错误请求)作为响应:

helpers.sendRequestFormData = function(protocol, port, hostname, method, path, contentType, auth, timeoutSeconds, postData, callback){
   var from = 'My Name <info@mydomain>';
   var to = 'validaddress@domain.com';
   var subject = 'Email test';
   var text = 'Testing sending email';

   var stringPayload = `--${config.mailgun.boundary}
                       \nContent-Disposition: form-data; name="from";
                       \nContent-type: multipart/form-data;
                       \nfrom="${from}";
                       \n--${config.mailgun.boundary}
                       \nContent-Disposition: form-data; name="to";
                       \nContent-type: multipart/form-data;
                       \nto="${to}";
                       \n--${config.mailgun.boundary}
                       \nContent-Disposition: form-data; name="subject";
                       \nContent-type: multipart/form-data;
                       \nsubject="${subject}";
                       \n--${config.mailgun.boundary}
                       \nContent-Disposition: form-data; name="text";
                       \nContent-type: multipart/form-data;
                       \ntext="${text}";
                       \n--${config.mailgun.boundary}\n`;

   // Construct the request
   var requestDetails = {
     'hostname' : hostname,
     'port': port,
     'method' : method,
     'timeout' : timeoutSeconds * 1000,
     'path' : path,
     'headers' : {
       'Authorization': auth,
       'Content-Type': contentType,
       'Content-Length': Buffer.byteLength(stringPayload)
     }
   };

   // Instantiate the request object (using either the http or https module)
   var _moduleToUse = protocol == 'http' ? http : https;
   var req = _moduleToUse.request(requestDetails, function(res){

     var responseStatus = res.statusCode;
     console.log(responseStatus);

     res.setEncoding('utf8');
     res.on('data', function(data){

       if(requestStatus == 200){
         callback(false, parsedData);
       }

     });
   });

   // Bind to the error event so it doesn't get thrown
   req.on('error',function(e){
     console.log(e);
     callback(true, {'Error': e});
   });

   // Bind to the timeout event
   req.on('timeout',function(){
     console.log('timeout');
     callback(true, {'Error': 'The request took much time and got timeout.'})
   });

   // Add the payload
   req.write(stringPayload);

   // End the request
   req.end();
 };

有人可以给我一些提示,指导或技巧吗?我对此有点不知所措,我敢肯定这可能很简单,在边界上使用分号和破折号进行反复试验,但仍然没有200状态响应代码。

非常感谢您!

1 个答案:

答案 0 :(得分:1)

我成功了,当前代码如下:

helpers.sendRequest = function(protocol, port, hostname, method, path, 

contentType, auth, timeoutSeconds, postData, callback){
   var stringPayload = querystring.stringify(postData);

   // Construct the request
   var requestDetails = {
     'hostname' : hostname,
     'port': port,
     'method' : method,
     'timeout' : timeoutSeconds * 1000,
     'path' : path
   };

   // Instantiate the request object (using either the http or https module)
   var _moduleToUse = protocol == 'http' ? http : https;
   var req = _moduleToUse.request(requestDetails, function(res){
     res.on('data', (d) => {
       if(res.statusCode == 200){
        callback(false);
       }else{
         console.log(res.statusCode);
         callback(true);
       }
     });
   });

   req.setHeader('Authorization', auth);
   req.setHeader('Content-Type', contentType);
   req.setHeader('Content-Length', Buffer.byteLength(stringPayload));

   // Add the payload
   req.write(stringPayload);

   // Bind to the error event so it doesn't get thrown
   req.on('error',function(e){
     console.log(e);
     callback(true, {'Error': e});
   });

   // Bind to the timeout event
   req.on('timeout',function(){
     console.log('timeout');
     callback(true, {'Error': 'The request took much time and got timeout.'})
   });

   // End the request
   req.end();
 };

我这样调用方法:

genericHelper.sendRequest('https', '443', 'api.mailgun.net', 'POST', '/v3/sandbox0630029a67f24517a9c3e383d2c6098e.mailgun.org/messages',
                    'application/x-www-form-urlencoded', ('Basic ' + Buffer.from(('api:'+ config.mailgun.ApiKeyTest)).toString('base64')), 5, emailRequestObject, function(err, data){

// Here I do what I need after sending the http request with success

});

我希望它能对某人有所帮助,所以问题出在内容类型上,我不得不将其更改为“ application / x-www-form-urlencoded”,然后还要将授权转换为Base64并包括Basic在base64中的配对之前。