0

我正在尝试在 node.js 中创建一个 Web 服务器,但我遇到了一个奇怪的问题。

服务器正确响应查看页面的请求,但是当我在某些浏览器上查看页面源时,节点服务器抛出错误

fs.js:379
  binding.open(pathModule.toNamespacedPath(path),
          ^

TypeError: path must be a string or Buffer
    at Object.fs.readFile (fs.js:379:11)
    at Server.<anonymous> (/ProjectFolder/index.js:32:6)
    at Server.emit (events.js:180:13)
    at parserOnIncoming (_http_server.js:642:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:117:17)

我想,也许查看源的请求有一个奇怪的请求路径,但是 a) 它说TypeError,所以它会在resolveFileName函数中出错。b) 视图源不会只是在客户端以不同的方式显示请求结果,而不对请求进行任何更改吗?

Google chrome: Error
MS Edge: OK
Internet Explorer: Error
Netscape 8: OK

这是我的代码:

文件系统:

> ProjectFolder
| > index.js
| > svrpath
| | > file.html

index.js:

var http = require('http');
var fs = require('fs');

function resolveFileName(req){
  var typs = {
    ".html": "text/html",
    ".css": "text/css",
    ".js": "text/javascript"
  };
  if(req === "/"){
    return {
      fname: "./svrpath/file.html",
      type: "text/html"
    };
  }else if(/^.*\.(html|css|js)$/.test(req)){
    return {
      fname: "./svrpath" + req,
      type: typs[req.replace(/^.*(?=\.(html|css|js)$)/, "")]
    };
  }else if(/^.*\/$/.test(req)){
    return {
      fname:"./svrpath" + req.replace(/\/$/, "") + ".html",
      type: "text/html"
    };
  }else{
    return "error400";
  }
}

http.createServer(function(req, res){
  var file = resolveFileName(req.url);
  fs.readFile(file.fname, function(err, data){
    if(err){
      throw err;
    }
    res.writeHead(200, {"Content-Type": file.type});
    res.end(data);
  });
}).listen();

svrpath/file.html

<!DOCTYPE html>
<html>
  <body>
    <p>Hello World!</p>
    <p>Some more content</p>
  </body>
</html>

工作示例

4

1 回答 1

2

您的浏览器默认要求 favicon.ico,您对此没有答案,这就是您有未定义路径的原因(没有这种情况)。您可以添加文件 favicon.ico 并为其创建条件:

function resolveFileName(req){
  var typs = {
    ".html": "text/html",
    ".css": "text/css",
    ".js": "text/javascript"
  };
  if(req === "/"){
    return {
      fname: "./svrpath/file.html",
      type: "text/html"
    };
  }else if(/^.*\.(html|css|js)$/.test(req)){
    return {
      fname: "./svrpath" + req,
      type: typs[req.replace(/^.*(?=\.(html|css|js)$)/, "")]
    };
  }else if(/^.*\/$/.test(req)){
    return {
      fname:"./svrpath" + req.replace(/\/$/, "") + ".html",
      type: "text/html"
    };
  }else if(req === "/favicon.ico"){
      return {
        fname: "./svrpath/favicon.ico",
        type: "image/x-icon"
      }
  }else{
    return "error400";
  }
}

于 2018-04-07T19:25:23.720 回答