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

我如何返回 json 对象而不是“Hello 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);
    });
});

请注意,您有两个res变量 - 一个是您发送回您自己的客户的响应,另一个是您从 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 回答