简体   繁体   中英

NodeJS create HTTPS Rest body request JSON

i'm trying to do a HTTPS REST request within nodejs using following Code:

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:

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]

I think it has something to do with stringify, maybe I have to convert it to JSON Format anyhow..

In the request's headers is specified the 'Content-Type': 'application/x-www-form-urlencoded' . You can try changing this to 'Content-Type': 'application/json' .

you need to change content-type.try like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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