如何从 Express 中的函数传递信息 get API in MEAN Stack

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

这里我有一个函数 hsResponse 如下所示,在 console.log 中,当我 运行 这个独立时,我得到了正确的 body 响应,但是现在我想在 app.get() 方法内部调用,我想将 hsResponse 的响应放到 app.get() API 响应中。

在 运行 设置 API 之后,我想获取 hsResponse 的 body(打印在 console.log 中的值)而不是根 API.

我怎样才能做到这一点?

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');
});

你可以把代码放在里面:

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
    });

});

为什么不使用传入参数回调的函数来处理请求结果:

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 上面的代码将每个请求的整个 api 响应缓冲到内存(正文)中,然后再将结果写回客户端,然后它就可以开始吃东西了如果同时有很多请求,会占用大量内存。 Streams,通过使用流,我们可以一次从 api 响应中读取一个块,将其存储到内存中并将其发送回客户端:

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);

});

参考:stream handbook