'How do I read a form-data response body in Node?
I do a post to https://api.instagram.com
but I don't know how to read the response. When I try console.log(response.body);
I get undefined
Here is my code:
var form = new FormData();
form.append('client_id','fc50049ba7df49b7b96535f892642366')
form.append('client_secret','6658e18d25e740e691c0cdcdd9adeabf')
form.append('grant_type','authorization_code')
form.append('redirect_uri','http://localhost:1992/oauth/ig')
form.append('code',req.query.code)
form.submit("https://api.instagram.com/oauth/access_token", (error, response) => {
console.log(`STATUS: ${response.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(response.headers)}`);
console.log(response.body)
var body = "";
response.setEncoding('utf8');
response.on('data', function(chunk) {
body += chunk;
});
response.on('end', function() {
console.log(body);
res.send(body);
});
});
Solution 1:[1]
The response
type from form.submit()
is IncomingMessage
, from http
. So you can do this:
res.on('data', (chunk) => {
console.log(chunk) // this is your response body
})
Solution 2:[2]
If you want to get a string you must do an toString:
res.on('data', (chunk) => {
console.log(chunk.toString()) // this is your response body
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | André Ribeiro |
Solution 2 | javier Tomas |