0

私は次のコードを持っています:

var http = require('http')
  ,https = require('https')
  ,fs = require('fs'),json;

var GOOGLE_API_KEY = process.env.GOOGLE_API_KEY;

var FUSION_TABLE_ID = "1epTUiUlv5NQK5x4sgdy1K47ACDTpHH60hbng1qw";

var options = {
  hostname: 'www.googleapis.com',
  port: 443,
  path: "/fusiontables/v1/query?sql=SELECT%20*%20"+FUSION_TABLE_ID+"FROM%20&key="+GOOGLE_API_KEY,
  method: 'GET'
};

http.createServer(function (req, res) {
  var file = fs.createWriteStream("chapters.json");
  var req = https.request(options, function(res) {
    res.on('data', function(data) {
      file.write(data);
    }).on('end', function() {
      file.end();
    });
  });
  req.end();
  req.on('error', function(e) {
    console.error(e);
  });
  console.log(req);
  res.writeHead(200, {'Content-Type': 'application/json'});
  res.end('Hello JSON');

}).listen(process.env.VMC_APP_PORT || 8337, null);

'Hello JSON'ではなくjsonオブジェクトを返すにはどうすればよいですか?

4

1 に答える 1

0

受信したデータをファイルに保存せず、代わりにローカル変数に入れてから、その変数を次の場所に送信しますres.end()

var clientRes = res;
var json = '';

var req = https.request(options, function(res) {
    res.on('data', function(data) {
        json += data;
    }).on('end', function() {
        // send the JSON here
        clientRes.writeHead(...);
        clientRes.end(json);
    });
});

2つの変数があることに注意してくださいres。1つは自分のクライアントに送り返す応答用で、もう1つはGoogleから受信する応答用です。前者と呼んでいclientResます。

または、情報を変更せずにプロキシする場合は、コールバックclientRes.write(data, 'utf8')内に配置できます。res.on('data')

http.createServer(function (clientReq, clientRes) {

    var req = https.request(options, function(res) {
        res.on('data', function(data) {
            clientRes.write(data, 'utf8');
        }).on('end', function() {
            clientRes.end();
        });

    clientRes.writeHead(200, {'Content-Type: 'application/json'});
    clientReq.end().on('error', function(e) {
        console.error(e);
    });

});
于 2012-12-12T16:09:36.220 に答える