我正在尝试在 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>