【问题标题】:Node.js app.js not displaying HTML page but HTML code insteadNode.js app.js 不显示 HTML 页面,而是显示 HTML 代码
【发布时间】:2014-02-05 07:21:00
【问题描述】:

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

【问题讨论】:

  • 试试response.writeHead(200, {'Content-Type': 'text/html'});
  • 根据您要加载的文件,您需要调整内容类型:例如text/htmltext/css
  • 谢谢!即使我只添加了 respnse.writeHead(200, {"Content-Type": "text/html"}); 我认为它也加载了 css 和 javascript因为我能够将它链接到一个 css 文件?
  • 哦等等不。如何显示所有 .css 文件?如果它们位于 html 页面的内部,我只能使用 css。我只是添加 response.writehead(200, {"Content-Type": "text/css"});在 app.js 一些随机的地方? javascript也一样?

标签: javascript html css node.js


【解决方案1】:

如果您尝试,您没有指定内容类型:

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 中显示错误页面,您还需要更新该内容类型。

【讨论】:

  • 谢谢!在 html 中显示错误页面会很棒。我知道如何在 response.write();但是我如何将它引导到一个让我们说 500.html 错误页面?
猜你喜欢
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-09
  • 2019-04-01
  • 2019-10-14
  • 2018-03-11
相关资源
最近更新 更多