nodejs https回调不更新全局变量 [英] nodejs https callback not updating global variable

查看:155
本文介绍了nodejs https回调不更新全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在nodejs中设置一个快速代理服务器,以代理Angular应用程序的API请求.代理端点是我无法控制的服务,并且不支持CORS或JSONP.为了进行测试,我在下面的代码示例中设置了一个虚拟http服务器,但实际上,这是一个远程域.

I'm setting up a quick proxy server in nodejs to proxy a API request for an Angular application. The proxy endpoint is a service I do not control and does not support CORS or JSONP. For testing, I setup a dummy http server in the code example below, but in reality this is a remote domain.

我很确定我的问题是由于nodejs的异步处理引起的,但是我不知道如何解决这个问题.我的通用makeRequest()函数似乎可以正常运行,它从远程服务器获取了预期的响应.我可以在成功的on('data')和on('end')事件处理程序中看到resultData字符串.但是,我不知道如何在restify的req.json()方法中将响应返回给浏览器.

I'm pretty sure my problem is due to asynchronous processing of nodejs, but I don't know how to solve this. My generic makeRequest() function seems to work ok, it gets the expected response back from the remote server. I can see the resultData string in the on('data') and on('end') event handlers with success. However, I don't know how to get the response back to the browser inside restify's req.json() method.

帮助!

var restify = require('restify');
var querystring = require('querystring');
var https = require('https');
var http = require('http');
var port        =  '8080';
var server = restify.createServer({
    name : "ProxyService"
});
var responseData = '';

// Generic request function
function makeRequest(host, endpoint, method, data, headers) {
    var dataString = JSON.stringify(data);

    var options = {
      host: host,
      path: endpoint,
      method: method,
      headers: headers
    };

    var req = https.request(options, function proxyrespond(res) {

      res.on('data', function(data) {
        console.log("DATA----", data);
        responseData += data;
      });

      res.on('end', function() {
        //probably need to do something here
      });
    });
    req.end();
    req.on('error', function(e) {
        console.error(e);
    });

    console.log("OPTIONS: ", options);
    console.log("DATA: ", responseData);
    req.write(dataString);
    req.end();
};

server.get('/getlist', function respond(req, res, next){
    var headers     =  {'Connection': 'close',
                        'Content-Type': 'application/json' };
    var host = 'localhost:9000';
    var endpoint = '/getlist';
    var auth = {auth-id: '12345', auth-token: '6789'}
    var data = req.data || '';

    // add authentication parms to the endpoint
    endpoint += '?' + querystring.stringify(auth);

    // if the request has headers, add them to the object
    for (var key in res.headers) {
        headers[key] = rest.headers[key];
    };

    makeRequest(host, endpoint, 'GET', data, headers);
    res.headers = {Connection: 'close'};
    res.json( responseData );
    return next();
});

http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen(9000);

server.listen(port, function(){
    console.log('%s listening at %s ', server.name , server.url);
});

推荐答案

通过回调函数返回:

// Generic request function
function makeRequest(host, endpoint, method, data, headers, callback) {
    .........
    var req = https.request(options, function proxyrespond(res) {
      // DO NOT declare responseData as global variable
      var responseData = '';
      res.on('data', function(data) {
        responseData = responseData + data;
      });

      res.on('end', function() {
        // RETURN VIA CALLBACK
        callback(responseData)
      });
    });
    .........
};

server.get('/getlist', function respond(req, res, next){
    .........

    makeRequest(host, endpoint, 'GET', data, headers, function (responseData) {
        res.headers = {Connection: 'close'};
        res.json( responseData );
        return next();
    });

});

这篇关于nodejs https回调不更新全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆