我可以在req.get中发送http请求吗?

好吧,可能是一个奇怪的问题,但通常当你有这样的代码

app.get('/', function(request, response) { response.render('pages/index'); }); 

您使用mongoDB并获取数据库中的相关数据以返回,但是如果我想对其他服务进行api调用以获取数据呢?

我正在使用请求库( https://github.com/request/request#streaming )

到目前为止我的代码看起来像这样

 request = require('request'); .... .... app.get( '/examplePage', function( request, response ) { request("http://www.google.com", function(error, response, body) { console.log(body); }); }); 

但我得到一个“TypeError:对象不是一个函数”,这是奇怪的,因为我只是复制和粘贴作为一个例子提供的代码在他们的github页面。 所以我只是改变了请求request.get(因为默认是一个GET,但我只是显式使用get方法),但我没有得到回应,或谷歌的HTML不返回。

所以基本上我甚至不确定我是否允许在app.get方法中使用请求方法调用,我假设这可能是问题?

request不是你认为它是在app.get函数内。 你应该这样改变它:

 request = require('request'); .... .... app.get( '/examplePage', function( req, res) { request("http://www.google.com", function(error, r, body) { console.log(body); }); }); 

这样你就不会覆盖你之前设置的任何variables。 当您尝试使用request模块时,它正在引用它在app.get调用中收到的请求参数,而不是函数。

你的代码中有两个叫做request对象, 请求模块和http调用中的路由请求 ,你可以将你的代码更新为:

 var request = require('request') ... app.get('/example', function (req, res) { request("http://googl.com", function (err, response, body) { console.log(body) }) }) 

同时考虑到resresponse对象不能有相同的名称,如果你这样做,后者将根据你使用的上下文来考虑。