显示本地主机信息的Node.js应用



我试图在node.js中构建一个应用程序,显示来自本地主机服务器的数据。我不能让它显示json文件中的信息。这是它现在显示的内容:头我的名字是:[宾语宾语]页脚

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("HEADERn");
    response.write("My name is:" + profile + "n");

    response.end("Footern");

 }
}
 module.exports.home = home;

您没有显示调用printMessage的位置,但是person参数是一个对象。如果你输入

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

对象被转换为JSON字符串。您只希望显示该对象中的单个字段。如果你想显示person的firstname字段,这可能会达到你的目的:

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