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

标签 javascript html css node.js

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

关于javascript - Node.js app.js 不显示 HTML 页面而是显示 HTML 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21160873/

相关文章:

jquery:当div达到一定高度时改变背景颜色

javascript - 用jquery重现css3变换

html - 将 CSS 内边距设置为负数

php - Jquery .load() 不返回 HTML(URL 中有 ""空格!)

html - 单选按钮列表 CSS 样式

javascript - 将 JSON 对象数组转换为字符串数组以与 C3.js 图表库一起使用

javascript - 单击“查看页面源代码”时,ReactJS 不显示 HTML

jquery - 将日期时间选择器添加到 TextBoxFor 字段 - MVC 5/Bootstrap 3

javascript - 按下回车键时不刷新页面

javascript - 清空 Vuex 对象时,如何避免 Vue 项目出现未定义错误?