Nodejs - parse response data without parsing as String? - node.js

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?

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

Related

How to get response header in node.js

I'm working on a nodejs project, I use request module to submit restful request and get response. (here is the module link: https://github.com/request/request)
Following the instruction, I should be able to get the response header by calling response.headers[''], however, seems it doesn't work, when I try to call var contentType = response.headers['Content-Type'], the contentType is undefined. (When I use postman, I could get Content-Type from the response). Anyone knows what's wrong?
This is the instruction from the site:
var request = require('request')
request(
{ method: 'GET'
, uri: 'http://www.google.com'
, gzip: true
}
, function (error, response, body) {
// body is the decompressed response body
console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
console.log('the decoded data is: ' + body)
}
In node, the headers are accessed by using lowercased names, so using response.headers['content-encoding'] is correct.
Your code snippet currently works for me and displays 'server encoded the data as: gzip.'

Empty response body

I am using superagent to make a request to Vimeo's Upload API.
My request looks as follows =
var request = require('superagent');
request
.post('https://api.vimeo.com/me/videos')
.set('Authorization', 'bearer ' + myAccessToken)
.set('Accept', 'application/vnd.vimeo.*+json;version=3.2')
.send({ type: "streaming" })
.end(function (error, response) {
//Code
}
I have to use the Accept header here to specify the version as mentioned in their documentation .
My problem is that the response.body is an empty object {}. The response.text is undefined - The response.status is 201.
I should get the response as shown in the documentation. But I get an empty object instead.
If I try the same request through POSTMAN, I get the response that I need. But using superagent I am not able to get it. Is there any additional configuration I need to do to get the response.body?

408 Timeout in NodeJS app requesting Github API

Following the documentation of the Github API to create an authorization for a NodeJS app.
I have the following code:
var _options = {
headers: {
'User-Agent': app.get('ORGANISATION')
},
hostname: 'api.github.com'
};
var oauth2Authorize = function () {
var path = '/authorizations?scopes=repo';
path += '&client_id='+ app.get('GITHUB_CLIENT_ID');
path += '&client_secret='+ app.get('GITHUB_CLIENT_SECRET');
path += '&note=ReviewerAssistant';
_options.path = path;
_options.method = 'POST';
var request = https.request(_options, function (response) {
var data = "";
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function () {
console.log(data);
});
});
request.on('error', function (error) {
console.log('Problem with request: '+ error);
});
};
And all I get is:
408 Request Time-out
Your browser didn't send a complete request in time.
Doing a GET request works though.
http.request() doesn't immediately send the request:
With http.request() one must always call req.end() to signify that you're done with the request - even if there is no data being written to the request body.
It opens the underlying connection to the server, but leaves the request incomplete so that a body/message can be sent with it:
var request = http.request({ method: 'POST', ... });
request.write('data\n');
request.write('data\n');
request.end();
And, regardless of whether there's anything to write() or not, you must call end() to complete the request and send it in its entirety. Without that, the server will eventually force the open connection to close. In this case, with a 408 response.

NodeJS receive data from a form, edit and send again

Basically I receive the values from a form with the function event:
var formData="";
req.on('data', function (chunk){
formData += chunk;
});
And I send those values again in another http.request:
req.on('end', function (){
var options = { port: conf.port, path: req.path,
host: conf.host, method: req.method , headers: req.headers};
authReq = http.request(options,
function (response){...});
authReq.write(formData);
authReq.end();
});
What I want is to add more data to the form receive from the previously form, like for example something like this:
var formData="client_id=XXX&client_secret=XXX&";
req.on('data', function (chunk){
formData += chunk;
});
But this is not working, after made the authReq.write(formData); looks like the data send is empty or wrong.... any suggestion ?
In the second request, the variable formData filled in the first request, will be empty.
You might need to use a session. (http://expressjs-book.com/forums/topic/express-js-sessions-a-detailed-tutorial/)
Also, from the looks of your code snippets, I suggest you look into http://passportjs.org/ for authentication :)

Making REST call from Node.js and sending response to browser

I am beginner to Node.js, so as per project requirements I am trying to call REST service from Node.js, I got information of how to call rest from this SO question. Here is the code to make rest call:
var options = {
host: url,
port: 80,
path: '/resource?id=foo&bar=baz',
method: 'POST'
};
http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk); //I want to send this 'chunk' as a response to browser
});
}).end();
The problem is I want to send chunk as a response to a browser, I tried res.write() but it is throwing me error "write method not found". I looked in docs everywhere, but all they give is console.log. Can anyone let me know how can I send that data as a response to a browser?
The callback to http.request is an instance of IncomingMessage, which is a Readable Stream that doesn't have a write method. When making an HTTP request with http.request, you cannot send a response. HTTP is a request-response-message-oriented protocol.
how can I send that data as a response to a browser?
For a browser to be able to get response, it must make a request first. You'll have to have a server running which calls the REST service when it receives a request.
http.createServer(function(req, res) {
var data = getDataFromREST(function(data) {
res.write(data);
res.end();
});
});

Resources