【问题标题】:NodeJS create HTTPS Rest body request JSONNodeJS 创建 HTTPS Rest body 请求 JSON
【发布时间】:2017-09-25 10:09:21
【问题描述】:

我正在尝试使用以下代码在 nodejs 中执行 HTTPS REST 请求:

var querystring = require('querystring');
var https = require('https');

var postData = {
    'Value1' : 'abc1',
    'Value2' : 'abc2',
    'Value3' : '3'
};
var postBody = querystring.stringify(postData);

var options = {
    host: 'URL'
    port: 443,
    path: 'PATH'
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': postBody.length
  }
};

var req = https.request(options, function(res) {
  console.log(res.statusCode);
  res.on('data', function(d) {
    process.stdout.write(d);
  });
});
req.write(postBody);
req.end();

req.on('error', function(e) {
  console.error(e);
});

请求有效,但不如预期。正文不会以 JSON 格式发送,看起来像:

RequestBody":"Value1=abc1&Value2=abc2&Value3=3

输出应该是这样的:

RequestBody":"[\r\n {\r\n \"Value3\": \"3\",\r\n \"Value2\": \"abc2\",\r\n \"Value1\": \"abc1\"\r\n }\r\n]

我认为它与stringify有关,也许我无论如何都必须将其转换为JSON格式..

【问题讨论】:

    标签: javascript json node.js https restful-url


    【解决方案1】:

    你需要改变内容类型。试试这样

    var querystring = require('querystring');
    var https = require('https');
    
    var postData = {
        'Value1' : 'abc1',
        'Value2' : 'abc2',
        'Value3' : '3'
    };
    var postBody = postData;
    
    var options = {
        host: 'URL'
        port: 443,
        path: 'PATH'
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
    
      }
    };
    
    var req = https.request(options, function(res) {
      console.log(res.statusCode);
      res.on('data', function(d) {
        process.stdout.write(d);
      });
    });
    req.write(postBody);
    req.end();
    
    req.on('error', function(e) {
      console.error(e);
    });
    

    【讨论】:

    • 同上错误:TypeError: First argument must be a string or Buffer
    【解决方案2】:

    我用以下方法解决了我的问题。

    jsonObject = JSON.stringify({
        'Value1' : 'abc1',
        'Value2' : 'abc2',
        'Value3' : '3' 
    });
    var postheaders = {
        'Content-Type' : 'application/json',
        'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')
    };
    

    【讨论】:

      【解决方案3】:

      在请求的标头中指定了'Content-Type': 'application/x-www-form-urlencoded'。您可以尝试将其更改为'Content-Type': 'application/json'

      【讨论】:

      • 我刚刚意识到您将数据作为字符串传递。这不是必需的,您只需传递一个对象即可。
      • 如果我通过删除 stringify 命令来尝试这个,我会得到以下错误:TypeError: First argument must be a string or Buffer
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      • 1970-01-01
      相关资源
      最近更新 更多