简体   繁体   English

NodeJS创建HTTPS Rest主体请求JSON

[英]NodeJS create HTTPS Rest body request JSON

i'm trying to do a HTTPS REST request within nodejs using following Code: 我正在尝试使用以下代码在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);
});

The request works but not as expected. 该请求有效,但不符合预期。 The Body will is not send in JSON Format and Looks like: 正文不会以JSON格式发送,如下所示:

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

The Output should look like that: 输出应如下所示:

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

I think it has something to do with stringify, maybe I have to convert it to JSON Format anyhow.. 我认为它与stringify有关,也许我必须将其转换为JSON格式。

In the request's headers is specified the 'Content-Type': 'application/x-www-form-urlencoded' . 在请求的标头中指定了'Content-Type': 'application/x-www-form-urlencoded' You can try changing this to 'Content-Type': 'application/json' . 您可以尝试将其更改为'Content-Type': 'application/json'

you need to change content-type.try like this 您需要像这样更改content-type.try

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);
});

I solved My Problem with the following. 我用以下方法解决了我的问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM