res.send() not returning anything - node.js

I am using the Vimeo library to display a specific video.
My Node.js code:
app.get("/video/:id", (req, res) => {
client.request(
{
method: "GET",
path: `/videos/${req.params.id}`,
},
(error, body) => {
if (error) {
console.log(error);
}
res.send(body.data);
});
});
console.log() before res.send() displays the object perfectly but does not send it, even though I get 200 response, the body is completely empty.

Related

getting and passing object to node js render method

I am playing around with the alpha vantage API and I am having trouble extracting the data in the else statement for viewing on the front end.
Here is my express route:
app.get('/', (req, res) => {
var url = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=apikey';
request.get({
url: url,
json: true,
headers: { 'User-Agent': 'request' }
}, (err, resp, data) => {
if (err) {
console.log('Error:', err);
} else if (resp.statusCode !== 200) {
console.log('Status:', resp.statusCode);
} else {
// data is successfully parsed as a JSON object:
// console.log(data);
}
})
res.render("index");
})
I want to pass the data variable in the else statement to res.render("index" {//get data into here});
I have tried assigning the data variable to another variable outside of request.get({}) but it does not seem to work. Any suggestions? :)
request.get is an asynchronous function, it means that everything inside the callback function below won't be executed immediately, it will wait until the request.get finish calling the endpoint and return the data then callback function will be executed.
// the callback function of `request.get`
(err, resp, data) => {
if (err) {
console.log('Error:', err);
} else if (resp.statusCode !== 200) {
console.log('Status:', resp.statusCode);
} else {
// data is successfully parsed as a JSON object:
// console.log(data);
}
})
In terms of execution flow, your res.render("index"); will be executed first before the callback function of request.get (it waits until the endpoint call finished), that's why you couldn't access data.
So, in order to res.render to access data, it should be put inside callback function so
(err, resp, data) => {
// ...other code
} else {
res.render('index', { data });
}
})
good reference to read about asynchronous https://www.freecodecamp.org/news/nodejs-eventloop-tutorial/
You can render it in the else statement.
app.get('/', (req, res) => {
var url = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=apikey';
request.get({
url: url,
json: true,
headers: { 'User-Agent': 'request' }
}, (err, resp, data) => {
if (err) {
console.log('Error:', err);
} else if (resp.statusCode !== 200) {
console.log('Status:', resp.statusCode);
} else {
res.render("index", {data}) // Change to something else
}
})
}}

res.send(body.data) is undefined

im trying to get another api using node request, but when i try to display body.data its return undefined
router.get('/', (req, res,next) => {
request('http://localhost:3000/api/v1/promos', (error, response, body) => {
if(error) {
res.send('An erorr occured')
console.log(error)
}
else {
res.send(body.data)
}
});
});
anyone know whats wrong
If the body of your request is JSON, then you have to parse it to turn it into a Javascript object so you can access the .data property.
You can do that by passing the json: true option to request() and it will parse the JSON for you.
Or, you can manually parse the body with let result = JSON.parse(body).
Here's how you set the json: true option:
router.get('/', (req, res,next) => {
request({
url: 'http://localhost:3000/api/v1/promos',
json: true
}, (error, response, body) => {
if(error) {
res.send('An erorr occured')
console.log(error)
}
else {
res.send(body.data)
}
});
});

Unable to access response object data outside the function in node js

I am using node js and making a call to spotify API and receive the response in body object, as shown in below code:
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, res, body) {
console.log(body)
});
This gives me output:
But now when I try to access the body object outside the function I get undefined. I think the problem is that I am making an asynchronous call and so before the response is received the statements where I make use of body variable outside function are executed. But I am a bit confused about how to get to the solution.
Any help is appreciated
Edit:
request.get(options, function(error, res, body) {
console.log(body)
response.render('user_account.html', {
data: body
})
});
And it gives the output:
Use promise.
You can try following:
const apiCall = () => {
return new Promise((resolve, reject) => {
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, res, body) {
if(error) reject(error);
console.log(body);
resolve(body);
});
});
}
apiCall().then((body) => {
// do your things here
})
.catch((err) => console.log(err));

I am learning about callback functions and API

Here I am learning about Callback functions and API to make weather app on node but when I am running the app on Terminal it says undefined I don't know why?
const request = require("request");
request({
URL: "http://maps.googleapis.com/maps/api/geocode/json?address=1301%20lombard%20street%20philadelphia",
json: true
}, (error, response, body) => {
console.log(body);
});
You are calling request incorrectly. You need to call it like so:
request("http://maps.googleapis.com/maps/api/geocode/json?address=1301%20lombard%20street%20philadelphia", {
json: true
}, (error, response, body) => {
console.log(body);
});
alternatively
request({
url: "http://maps.googleapis.com/maps/api/geocode/json?address=1301%20lombard%20street%20philadelphia",
json: true
}, (error, response, body) => {
console.log(body);
});
Notice the url property in lowercase, whereas yours was uppercase
Refer to https://github.com/request/request#requestoptions-callback

How to pass the information from function in the Express get API in MEAN Stack

Here I have a function hsResponse which is as below and in the console.log I am getting the proper body response when I run this standalone, but now I wanted call inside the app.get() method and I wanted to put the response of hsResponse to the app.get() API response.
After running the API I wanted to get the body (the value which is printed in the console.log) of hsResponse instead of Root API.
How can I achieve this?
var hsResponse = request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}, function (error, response, body) {
console.log(body);
});
app.get('', (req, res) => {
res.send('Root API');
});
Why not use a function with a callback passed in parameter to handle the request result:
var hsResponse = function (done) {
// done is a function, it will be called when the request finished
request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}, function (error, response, body) {
if (error) return done(error);
done(null, body);
});
}
app.get('', (req, res) => {
hsResponse( function (err, body) {
if (err) throw err;
// get body here
res.send('Root API');
} );
});
Edit the code above buffers up the entire api response into memory (body) for every request before writing the result back to clients, and it could start eating a lot of memory if there were many requests at the same time. Streams, by using streams we could read one chunk at a time from the api response, store it into memory and send it back to the client:
app.get('', (req, res) => {
request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}).pipe(res);
});
Reference: stream handbook
You can just put the code inside:
app.get('', (req, res) => {
var hsResponse = request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}, function (error, response, body) {
res.send(body); //<-- send hsResponse response body back to your API consumer
});
});

Resources