Why I am getting request for /recieved { [Error: ENOENT, open ''] errno: 34, code: 'ENOENT', path: '' } error?

Why I am getting request for /recieved { [Error: ENOENT, open ''] errno: 34, code: 'ENOENT', path: '' } error?

当我执行这段代码时,它给我 errno: 34, code: 'ENOENT' error 。 我写了一个简单的 html 你好世界页面。 它应该在端口 3000 上 运行 时简单地打印 hello world 但每次它都显示相同的错误。 我现在的node版本是v0.10.38

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

http.createServer(function(request, response) {

var pathname =url.parse(request.url).pathname;

console.log("request for "+ pathname + "recieved");

fs.readFile(pathname.substr(1), function (err, data) {
    if(err){
        console.log(err);
        response.writeHead(404,{'Content-Type': 'text/html'});
    }else{
        response.writeHead(200,{'Content-Type': 'text/html'});
        response.write(data.toString());
    }
    response.end();
});
}).listen(3000);

console.log("server running at 3000");

你的代码对我来说工作得很好。我认为当您发送请求时,您是在要求它提供一个不存在或路径信息不正确的文件。这就是错误告诉您的内容,无法找到提供给 fs.readFile 调用的路径。我做了以下事情:

1) 将代码复制到文件 /home/username/Desktop/test.js (Ubuntu 12.04)

2) 打开 chromium 网络浏览器

3) 在 URL 框中输入 127.0.0.1:3000//etc//fstab 并按回车键,其中 127.0.0.1:3000 会导致浏览器自行在端口 3000 查找服务器机器

文件 /etc/fstab 已读取并成功显示到浏览器中 window。

我的猜测是,当您输入 URL 时,您要求的文件超出范围或路径错误。如果我试图通过完整路径查找不存在的文件,我会得到相同的结果:{ [Error: ENOENT, open 'whereIsMyFile'] errno: 34, code: 'ENOENT', path: 'whereIsMyFile'}

如果您确实请求与 node.js 脚本位于同一目录中的文件,则不需要完整路径。例如,文件可以自己读取:127.0.0.1:3000/test.js