简体   繁体   中英

Node.js app.js not displaying HTML page but HTML code instead

Im having problem with my app.js in node not displaying my html page but my html code instead. I don't really know what to do so some help would be greatly appreciated. I would like to be able to load html, javascript and css from my public folder. This is my app.js code:

var http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs")

http.createServer(function(request, response) {

var uri = url.parse(request.url).pathname
    , filename = path.join(process.cwd(), uri);

path.exists(filename, function(exists) {
  if(!exists) {
    response.writeHead(404, {"Content-Type": "text/plain"});
    response.write("404 Not Found\n");
    response.end();
    return;
}

if (fs.statSync(filename).isDirectory()) filename += 'public/index.html';

fs.readFile(filename, "binary", function(err, file) {
  if(err) {        
    response.writeHead(500, {"Content-Type": "text/plain"});
    response.write(err + "\n");
    response.end();
    return;
  }

  response.writeHead(200);
  response.write(file, "binary");
  response.end();
  });
 });
}).listen(process.env.PORT, process.env.IP);

console.log("Static file server running./\CTRL + C to shutdown");

You are not specifying the content type, if you try:

fs.readFile(filename, "binary", function(err, file) {
if(err) {        
    response.writeHead(500, {"Content-Type": "text/plain"});
    response.write(err + "\n");
    response.end();
    return;
  }

  response.writeHead(200, {'Content-Type': 'text/html'});
  response.write(file, "binary");
  response.end();
  });
 });
}).listen(process.env.PORT, process.env.IP);

That should work. If you want to display the error page in html, you will want to update that content type as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM