NodeJS如何调试https.request和request.post输出之间的区别?

时间:2018-07-17 02:15:22

标签: node.js xml https request

由于某种原因,第三方API接受我的request.post请求,但不接受我的https.request。后者返回的错误是XML无效或格式错误。我宁愿使用https而不是请求,因为它会增加不必要的开销。

我如何调试这两个功能,以便我可以将https.request输出与request.post一个匹配?

request.post

request.post({url: 'https://api.example.com/post.php', form: { xml: full_xml_data }}, function(err, resp, xml){
  // request is successful
});

https.request

let options = {
  "hostname": api.example.com,
  "port": 443,
  "path": '/post.php',
  "method": "POST",
  "headers": {
    "Content-Type": "application/x-www-form-urlencoded",
    "Content-Length": full_xml_data.length
  }
};
let req = https.request(options, (res) => {
  let xml="";
  res.on("data", function(data){ xml+=data; });
  res.on("end", function(){
    // request is not successful, respons from API is that xml is invalid/malformed
  });
});
req.on("error", (err) => {
  // error handler
});

let post_data = querystring.stringify({"xml":full_xml_data});
// i have also tried: let post_data = 'xml='+encodeURIComponent(full_xml_data);
req.write(post_data);
req.end();

任何解决此问题的想法将不胜感激! 托马斯

1 个答案:

答案 0 :(得分:1)

我注意到的一件事是,在第二个请求中,您将Content-Length设置为原始数据长度,而不是编码数据长度。它必须是您实际发送的数据的长度。 http模块的文档建议您使用:Buffer.byteLength(encoded_data)来获得如下长度:

let post_data = querystring.stringify({"xml":full_xml_data});

let options = {
  "hostname": api.example.com,
  "port": 443,
  "path": '/post.php',
  "method": "POST",
  "headers": {
    "Content-Type": "application/x-www-form-urlencoded",
    "Content-Length": Buffer.byteLength(encoded_data)    // put length of encoded data here
  }
};
let req = https.request(options, (res) => {
  let xml="";
  res.on("data", function(data){ xml+=data; });
  res.on("end", function(){
    // request is not successful, respons from API is that xml is invalid/malformed
  });
});
req.on("error", (err) => {
  // error handler
});

req.write(post_data);
req.end();