簡體   English   中英

在index.html上創建node.js服務器時未呈現擴展文件

[英]Extension files not rendered when creating node.js server on index.html

我想在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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM