Friday 14 April 2017

Node HTTPS Request – MalformedJsonException

I'm trying to make a POST request using node/HTTPS, but I keep getting this error:

BODY: {"message":"MalformedJsonException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 11 path $","mdcKey":""}

Here's the code that initiates the request:

  const https = require('https');

  const querystring = require('querystring');

  const POSTData = querystring.stringify({
    'addressTo': 'myemail@address.com',
    'subject': 'testing your email template',
    'templateName': 'genericTemplate',
    'bodyText': 'this is a test'
  });

  console.log(POSTData);

  const HTTPOptions = {
    hostname: 'url.com',
    port: 00000,
    path: '/path',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    }
  };

  const HTTPSrequest = https.request(HTTPOptions, (response) => {
    console.log(`STATUS: ${res.statusCode}`);
    console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
    response.setEncoding('utf8');
    response.on('data', (chunk) => {
      console.log(`BODY: ${chunk}`);
    });
    response.on('end', () => {
      console.log('No more data in response.');
    });
  });

  HTTPSrequest.on('error', (error) => {
    console.log(`problem with request: ${error}`);
  });

  // write data to request body
  HTTPSrequest.write(POSTData);
  HTTPSrequest.end();

I'm assuming it's the POSTData that is the "malformed JSON", here's what it looks like stringified:

addressTo=name%40companyname.com&subject=testing%20your%20email%20template&templateName=genericTemplate&bodyText=this%20is%20a%20test

I'm not sure what I'm doing that is causing the malformed JSON. What am I missing?



via timothym

No comments:

Post a Comment