[AngularJS]与 nodeJS 返回 Json

发布时间: 2017/4/16 20:35:15
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我试着学习 nodeJS 和 AngularJS 在这里使用的氏族可用的 API,冲突https://developer.clashofclans.com/#/

我 JSON api 返回被截断,我不知道如何得到充分的回应。

还有我 app.js 作文与节点和快递︰

var   express       = require('express')
, https         = require('https')
, bodyParser    = require('body-parser')
, request       = require('request')
, app           = express()
, http_port     = 3000;

app.use(express.static(__dirname + '/public'));
app.use(bodyParser());

var options = {
    host: 'api.clashofclans.com',
    port: 443,
    path: '/v1/clans/' + encodeURIComponent("#PP8JC9RQ"),
    headers : {
    accept : "application/json",
    authorization : "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6IjI4YTMxOGY3LTAwMDAtYTFlYi03ZmExLTJjNzQzM2M2Y2NhNSJ9.eyJpc3MiOiJzdXBlcmNlbGwiLCJhdWQiOiJzdXBlcmNlbGw6Z2FtZWFwaSIsImp0aSI6ImQ4Njg1OGFhLWQzZTUtNDNiOC05MTM1LTBjNzI1ZjI4OGFiMiIsImlhdCI6MTQ1NjMwMTE5MSwic3ViIjoiZGV2ZWxvcGVyLzk1YWM0YjdmLTY5NTQtMDE3MC01ZjAyLTcxNjY1ZDMzYjUwNyIsInNjb3BlcyI6WyJjbGFzaCJdLCJsaW1pdHMiOlt7InRpZXIiOiJkZXZlbG9wZXIvc2lsdmVyIiwidHlwZSI6InRocm90dGxpbmcifSx7ImNpZHJzIjpbIjg3LjIzMS4yMTMuMTU0Il0sInR5cGUiOiJjbGllbnQifV19.SYqeSAF-0_bM1eS2-hnovvj5j-I0SQpdr_kySIiBKw9OkrNuBzZAOAOkiH3fzdKSkcHaJfXzWdXr8JozFfAmJA"
},
method: 'GET'
};

//  Route par défaut
    app.get("/members", function(req, res) {
    console.log("-------------------------------------\n\nroot path !! Let's get clan infos from coc api\n\n-------------------------------------");
    var req = https.request(options, function(response){

        response.on('data', function (chunk) {          
            console.log('BODY: ' + chunk);
            //    in console JSON is full but in my html JSON is truncated..
            res.send(chunk);
        });         
    });

    req.on('error', function(e) {
        console.log('problem with request: ' + e.message);
    });

    req.end();

    });


app.listen(http_port,function(){
    console.log("Listening on " + http_port);
});

如果有人可以教到一个角落:)

解决方法 1:

您的代码发送响应的第一个区块马上回给用户。你需要等待,直到完成整个 HTTP 响应。这样试试︰

app.get("/members", function(req, res) {
    var req = https.request(options, function(response){
    var httpResult = '';
    response.on('data', function (chunk) {          
        console.log('BODY: ' + chunk);
        httpResult += chunk;
    });         
    response.on('end', function() {
       res.send(httpResult);
    });
});

req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
});

req.end();

});

看看如何我将追加到 var 每次调用时数据事件,当它做-然后我送输出。

赞助商