2015-05-24 33 views
0

我試圖在node.js中構建一個顯示本地主機服務器數據的應用程序。我無法讓它顯示來自我的json文件的信息。這就是它現在顯示: HEADER 我的名字是:[對象的對象] 頁腳顯示本地主機信息的Node.js應用程序

app.js文件:

var router = require('./router.js'); 
//Problem: We need a simple way to look at a person's name, address, phone number and pictures 
//Solution: Use Node.js to perform the profile look ups and serve our template via HTTP 

// Create a web server 
var http = require('http'); 
http.createServer(function (request, response){ 
    router.home(request, response); 

    }).listen(8080, "127.0.0.1"); 
    console.log("Server running at localhost:3000"); 

profile.js file: 


    var http = require("http"); 

    function printMessage(person) { 
    var message = "My name is " + person 
    document.write(printMessage()); 
} 

var request = http.get("http://localhost:8080/person", function(response){ 
var body = ""; 
//Read the data 
response.on('data', function(chunk) { 
    body += chunk; 
}); 
response.on('end', function(){ 
    var person = JSON.parse(body); 
    var profile = person[0].name.firstName; 
}); 
request.on("error", function(error){ 
response.end("ERROR"); 
}); 

}); 

router.js文件:

var profile = require("./profile.js"); 


//Handle HTTP route GET/and POST/i.e. Home 
function home(request, response) { 
//if url == "/" && GET 
if(request.url === "/"){ 
    //show index page 
    response.writeHead(200, {'Content-Type': 'text/plain'}); 
    response.write("HEADER\n"); 

    response.write("My name is:" + profile + "\n"); 


    response.end("Footer\n"); 


} 
} 
module.exports.home = home; 

回答

0

你是沒有顯示你打電話給printMessage的地方,但是person參數是一個對象。如果您嘗試類似

var message = "My name is " + JSON.stringify(person); 

該對象將轉換爲JSON字符串。你只想顯示這個對象的單個字段。所以,如果你想顯示人的名字字段,所以這可能會做你想做的事情:

var message = "My name is " + person[0].name.firstName; 

取決於你的對象的樣子。

+0

我試過實現var message =「我的名字是」+ person [0] .name.firstName;但結果是一樣的。 –

相關問題