Reputation: 878
On the node/express side I'm trying to make an get request to an endpoint I just created.
What is the correct way to do this? Can I use the fetch library (isomorphic-fetch)
My attempt:
router.get('/displayweather', function(req, res) {
fetch('/weather')
.then(function(response){
res.send(response);
});
});
router.get('/weather', function(req, res){
var fetchUrl = 'http://api.wunderground.com/api/xyz-token/conditions/q/CA/San_Francisco.json';
fetch(fetchUrl)
.then(function(response){
if (response.status >= 400) {
throw new Error("Bad request response from server");
}
return response.text();
}).then(function(body) {
res.send(body);
});
});
Where there is another router.get(..) method retrieving weather data using an external API
Upvotes: 0
Views: 918
Reputation: 63524
I'd forget about that first part and concentrate on that code you added:
Server
router.get('/weather', function(req, res){
var fetchUrl = 'http://api.wunderground.com/api/xyz-token/conditions/q/CA/San_Francisco.json';
fetch(fetchUrl)
.then(function(response){
if (response.status >= 400) {
throw new Error("Bad request response from server");
}
// return json
return response.json();
}).then(function(body) {
// but stringify it when you send it
res.send(JSON.stringify(body));
});
});
Client
fetch('/weather')
.then(function (json) {
return JSON.parse(json);
})
.then(function (data) {
// do something with the data
})
Upvotes: 1