繁体   English   中英

Node.js app.js不显示HTML页面而是显示HTML代码

[英]Node.js app.js not displaying HTML page but HTML code instead

我在节点中的app.js出现问题,而不显示我的html页面,但显示了我的html代码。 我真的不知道该怎么办,因此将不胜感激。 我希望能够从公共文件夹中加载html,javascript和css。 这是我的app.js代码:

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");

如果尝试,则不指定内容类型:

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);

那应该工作。 如果要以html显示错误页面,则也将要更新该内容类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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