2016-10-09 101 views
0

我是Node.js中的新成員,遇到問題。如何將數據從JSON保存到NodeJS中的變量中

我想從我從github API下載的JSON對象保存數據。

var http = require("http"); 
var express = require('express'); 
var app = express(); 
var github = require('octonode'); 
var client = github.client(); 

app.set('port', process.env.PORT || 8000); 

var server = app.listen(app.get('port'), function() { 
    console.log('Express server listening on port ' + server.address().port); 
}); 

app.get('/getUsers', function (req, response) { 

    response.writeHead(200, {'Content-Type': 'text/json'}); 
    var result; 

    client.get('/users/angular/repos', {}, function (err, status, body, headers) { 
     result = response.write(JSON.stringify(body)); 
     console.log(result); //JSON object 
     return result; 
}); 

console.log(result); //undefined 

}); 

如何將對象中的數據保存到單個變量?

(我想然後將其轉換爲數組並獲取一些有用的數據)。

+0

如果您正在對'body'進行字符串化,是不是'body'已經是一個對象? –

回答

0

您不會在異步調用之外獲得結果,因爲它尚未定義。要獲取該值,可以調用查詢回調中的方法,或使用異步模塊並傳遞它。

app.get('/getUsers', function (req, response) { 

    response.writeHead(200, {'Content-Type': 'text/json'}); 
    var result; 

    client.get('/users/angular/repos', {}, function (err, status, body, headers) { 
     result = response.write(JSON.stringify(body)); 
     console.log(result); //JSON object 
     doSomeOperationOnResult(result) 
}); 
}); 

function doSomeOperationOnResult(result){ 
//Your operating code 
} 
+0

它正在工作,謝謝 – majkel170792

相關問題