javascript - 在index.html 上创建node.js 服务器时未呈现扩展文件

标签 javascript html node.js

我想在 request.url = '/' 时显示我的 index.html。 然而,似乎与我的index.html 文件相关的扩展文件没有被渲染。

这是我的 server.js 文件:

var verifyMimeType = true;
var port = 8000;
var serverURL = "127.0.0.1";

console.log("Starting web server: " + serverURL + ":" + port);

var server = http.createServer(function(req,res){
  var parsedURL = url.parse(req.url);
  console.log("Parsed URL: " + parsedURL);

  if(req.url == '/'){
    filename = '/public/index.html'
  }
  console.log("Filename is: " + filename);
  // sets the extention of the filename
  var ext = path.extname(filename);
  var localPath = __dirname;
  console.log("Local path: "+ localPath);
  var validExtentions ={
    ".html" : "text/html",
    ".js": "application/javascript",
    ".css": "text/css",
    ".txt": "text/plain",
    ".jpg": "image/jpeg",
    ".gif": "image/gif",
    ".png": "image/png"
  };

  var validMimeType = true;
  var mimeType = validExtentions[ext];
  if(verifyMimeType){
    validMimeType = validExtentions[ext] != undefined;
  }

  if(validMimeType){
    localPath += filename;
    fs.exists(localPath, function(exists){
      if(exists){
        console.log("Serving file: " + localPath);
        getFile(localPath,res,mimeType);
      }
      else{
        console.log("File not found: " + localPath);
        res.writeHead(404);
        res.end();
      }
    });
  }
  else{
    console.log("Invalid file extention detected: " + ext);
    console.log("Invalid file name: " + filename);
  }
});

server.listen(port,serverURL);

var getFile = function(localPath, res, mimeType){
  fs.readFile(localPath, function(err, data){
    if(err){
      console.log("Error with reading file: ("+ err + ")");
      res.writeHead(500);
      res.end();
    }
    else{
      res.setHeader("Content-Length", data.length);
      if(mimeType != undefined){
        res.setHeader("Content-Type", mimeType);
      }
      res.statusCode = 200;
      // the end does two things, it write to the response and
      // ends the response.
      res.end(data);
    }
  });
}

最佳答案

当 url 不是 / 时,您忘记初始化 filename。以下是修复示例:

if(req.url == '/') {
  filename = '/public/index.html'
} else {
  filename = path.basename(parsedURL.pathname);
}

关于javascript - 在index.html 上创建node.js 服务器时未呈现扩展文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41714689/

相关文章:

javascript - 查找数组对象的值差异

javascript - 如何使用 Node.js 在服务器端管理多个 JS 文件

mysql - 如何从 mysql 中的内连接查询中删除重复行

html - 居中多行 float 元素

node.js - 确定是否向 Firebase 实时数据库添加或删除数据

node.js - Node - 延续本地存储

c# - 混合 Razor 和 Javascript 代码

javascript - 拉伸(stretch) <img> 以适合整个屏幕,而不保持宽高比且没有滚动条

html - 如何使用CSS隐藏字符串中的一些文本

node.js - Azure Cosmos + Gremlin NodeJS,如何以脚本形式提交流畅的查询(不是字节码——我知道它还不支持)