cn1993 cn1993 - 4 months ago 24
Node.js Question

Sending a GET request JSON object from server side to client side in Node.JS

I'm new Node.js and server side scripting in general and am currently practicing with the brewerydb-node wrapper found here(https://www.npmjs.com/package/brewerydb-node)

I currently have the following server side code that will log the appropriate JSON object to the command line

var express = require('express');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var BreweryDb = require('brewerydb-node');
var brewdb = new BreweryDb([api-key here]);
var request = require('request');

app.use(bodyParser.json());

brewdb.breweries.getById("g0jHqt", {}, function(err, beer) {
if(err) {
console.log(res.statusCode());
} else {
console.log(beer.name);
}
})

app.listen(8000, function() {
console.log("Listening at http://localhost:8000");
})


I'm not sure how I would go about having this object be sent as a response to which I could parse through with my client side code as there are no 'res' or 'req' parameters in this wrapper.

Answer

You want to wrap your request in a route, like so:

var express = require('express');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var BreweryDb = require('brewerydb-node');
var brewdb = new BreweryDb([api-key here]);
var request = require('request');

app.use(bodyParser.json()); 

app.get('/breweries/:id', function(req,res){
  // in here a request to http://localhost:8000/breweries/g0jHqt will fetch the same as your example code
  brewdb.breweries.getById(req.params.id, {}, function(err, beer) {
    if(err) {
        console.error(err);
        res.status(500).send("An error occurred"); 
    } else if(beer) { // we found the beer
        res.send(beer);
    } else{
        res.status(404).send('We could not find your beer');
    }
  })
});

app.listen(8000, function() {
    console.log("Listening at http://localhost:8000");
})