Node.js app that displays information from a localhost

时间:2015-05-24 21:15:44

标签: javascript node.js

I'm trying to build an app in node.js that displays the data from a localhost server. I can't make it display the information from my json file. This is what it displays now: HEADER My name is:[object Object] Footer

app.js file:

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 file:

   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;

1 个答案:

答案 0 :(得分:0)

You are not showing where you call printMessage, but the person parameter is an object. If you try something like

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

the object is converted to a JSON string. You only want to display a single field from this object. So if you want to show the firstname field of person, so this will probably do what you want:

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

depending on how your object looks like.