为什么http结尾会在请求结束时发生

时间:2016-11-17 20:59:15

标签: socket.io httprequest

你好,我不明白我的代码出了什么问题 当我在第49行执行v.comment = JSON.parse(body_detail).comment时,数组跳闸第32行未填充,我尝试在之后发送它。 我做了[i] .comment也没有成功。 我的日志说它是因为我在函数外部执行on.emit()。 如果您有一些建议,我会很高兴听到它。 THX。

    var app = require('express')();
var http = require('http').Server(app);
var https = require("https");
var io = require('socket.io')(http);
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  socket.on('push', (msg) => {
    var options = {
      "method": "GET",
      "hostname": "public-api.blablacar.com",
      "port": null,
      "path": "/api/v2/trips?"+
      "fn="+msg.fn+
      "&tn="+msg.tn+
      "&db="+msg.db+
      "&limit=10"+
      "&locale=fr_FR"+
      "&_format=json",
      "headers": {
        "accept": "application/json",
        "key": "xxx"
      }
    };
    var q = https.request(options, (res) => {
      var chunks = [];
      res.on("data", (chunk) => { chunks.push(chunk) });
      res.on("end", () => {
        var body = Buffer.concat(chunks);
        var trips = JSON.parse(body).trips;
        trips.forEach((v,i) => {
          var options = {
            "method": "GET",
            "hostname": "public-api.blablacar.com",
            "port": null,
            "path": "/api/v2/trips/"+v.permanent_id,
            "headers": {
              "accept": "application/json",
              "key": "xxx"
            }
          };
          var q = https.request(options, (res) => {
            var chunks_detail = [];
            res.on("data", (chunk) => { chunks_detail.push(chunk) });
            res.on("end", () => { 
              var body_detail = Buffer.concat(chunks_detail);
              v.comment = JSON.parse(body_detail).comment
            });   
          });
          q.end();   
        }, this);      
        io.emit('pull', trips);    
      });
    });
    q.end();   
  });
});
http.listen(3000, () => { console.log('listening on *:3000') });
 //console.log(body.toString());

0 个答案:

没有答案