【发布时间】: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