【问题标题】:HTTPS Request (using https nodejs module) of type 'form-data/multipart' not working'form-data/multipart' 类型的 HTTPS 请求(使用 https nodejs 模块)不起作用
【发布时间】:2018-11-12 03:00:51
【问题描述】:

我有以下 curl 请求,它运行良好且符合预期:

curl --user 'api:MY_API_KEY' https://api.mailgun.net/v3/mydomain/messages --form from='我的名字 ' --form to=validaddress@domain.com --form 主题='你好 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 状态响应代码。

非常感谢您!

【问题讨论】:

  • 您的https 请求是否将port 设置为443。我没有看到任何条件
  • 嗨@front_end_dev,是的,端口是在函数的参数中传递的
  • 如果您有 400 错误,这意味着您的请求在某种程度上是错误的。尝试打印出两个请求并检查它们为什么不同。
  • 嗨@MarioSantini这是一个很好的提示是的,我会搜索打印出一个curl请求,也许是-verbose标签或其他什么?我会搜索谢谢!
  • Javascript 中的反引号是定义模板字符串的一种方式,所以我认为你可以去掉 \n 字符(和空格)...跨度>

标签: javascript node.js https multipartform-data


【解决方案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 中的对之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多