我一般都使用新的Node.js和服务器端脚本,目前正在使用此处的brewerydb-node包装器进行练习(https://www.npmjs.com/package/brewerydb-node)
我目前有以下服务器端代码,它将相应的JSON对象记录到命令行
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");
})
我不确定如何将此对象作为响应发送,我可以使用我的客户端代码解析,因为没有' res'或者' req'这个包装器中的参数。
答案 0 :(得分:1)
您希望将请求包含在路由中,如下所示:
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");
})