user3334871
user3334871

Reputation: 1361

Nodejs - parse response data without parsing as String?

I'm following some tutorials online, and I'm trying to parse a response from an HTTP post call from my node app. My app acts as an interceptor, we make a POST request to the interceptor app, I transform the data, then I post it to another client to perform some action, and then I want to return the response from the other app as my app's response. Below is the code I use to make the post:

const request = http.request(options, function(response) {
 console.log('STATUS: ' + response.statusCode);
 console.log('HEADERS: ' + JSON.stringify(response.headers));
 response.setEncoding('utf8');
 response.on('data', function (chunk) {
   console.log('BODY: ' + chunk);
   //res is the actual response object to my app's own post function
   res.status(response.statusCode).send({response:chunk});
 });
});

Now, the response to the post object looks like ["Hey there! How can I help you?"].

However, when I return that as a response to my API, the body looks like:

"response": "[\"I am doing well. Thank you for asking.\"]\n".

I want to interact with the array that is returned, grab the string at index 0, and return that as my response. Is this possible?

Upvotes: 0

Views: 117

Answers (1)

Ankit
Ankit

Reputation: 1214

Have you tried?

res.setHeader('content-type','application/json');
res.status(response.statusCode).send(chunk);

Upvotes: 1

Related Questions