1

I have coded an HTTPS function using the native https module from NodeJS to get some JSON from an API.

When I'm doing a GET request I'm getting the JSON fine, but when I have to make a PUT request I got the JSON but I can't convert that into an object.

answer from GET:

{
  items: [
    { dsname: 'A09999' },
    { dsname: 'A09999.ALLFILES.TEMP' },
  ],
  returnedRows: 16,
  JSONversion: 1
}

answer from PUT:

{
  'cmd-response-key': 'C8124546',
  'cmd-response-url':'https://myhost/zosmf/restconsoles/consoles/ibmusecn/solmsgs/C8124546',
  'cmd-response-uri': '/zosmf/restconsoles/consoles/ibmusecn/solmsgs/C8124546',
  'cmd-response':
   ' IEE457I 16.32.55 UNIT STATUS 464\r UNIT TYPE STATUS        VOLSER' }

My code:

const makeRequest = options =>
    new Promise(function(resolve, reject) {
        let results = https.request(options, res => {
            res.setEncoding('utf8');
            let body = '';

            res.on('data', data => {
                body += data;
            });
            res.on('end', () => {
                body = JSON.parse(body);
                console.log('body :', body);
                resolve(body);
            });
        });
        if (options.body) {
            // results.write(options.body);
            results.write(JSON.stringify(options.body),['Transfer-Encoding', 'chunked']);
        }
        results.on('error', e => {
            reject(e);
        });
        results.end();
    });
1
  • Neither of these is valid JSON. But maybe you are showing the already parsed JSON? Can't tell. Commented Feb 13, 2019 at 23:50

1 Answer 1

1

Well what you are getting back from the post is not a valid json object. This bit right here:

'cmd-response':
   ' IEE457I 16.32.55 UNIT STATUS 464\r UNIT TYPE STATUS        VOLSER'' }

Notice how at the end, VOLSER is followed by to ''. This ends the string starting the value and opens a new string. This is invalid JSON.

Also, I'd recommend using a library like axios or request from npm. Well written, widely used, and not as low level as using the https module directly.

Sign up to request clarification or add additional context in comments.

2 Comments

That second ' was pasted by mistake, i'm not getting it on the answer, anyway it's not comeing as expected :(
By the way i just tried with AXIOS and i'm getting the answer in same format... i will report it for who is responsible for maintain that api, since i can just think it may be a problem in the side of the api that is not proper handling the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.