node.js 404 找不到文件错误

node.js 404 file not found error

var http = require('http'),
fs=require('fs'),
path=require('path'),
host ='127.0.0.1',
port='9001';
var mimes = {
    ".htm":"text/html",
    ".css":"text/css",
    ".js":"text/javascript",
    ".gif":"text/gif",
    ".jpg":"text/jpeg",
    ".png":"text/png"
}
var server = http.createServer(function(req,res){
    var filepath =(req.url==='/')?('./index.htm'):('.'+req.url);
    var contentType = mimes[path.extname(filepath)];
    //check file exists or not
    fs.exists(filepath,function(file_exists){
        if(file_exists)
        {
                res.writeHead(200, {'Content-Type' : contentType});
                var streamFile = fs.createReadStream(filepath).pipe(res);
                streamFile.on('error',function(){
                    res.writeHead(500);
                    res.end();
                })
        }
        else
        {
            res.writeHead(404);
            res.end("sorry we could not find the file you requested");
        }
    })
}).listen(port,host,function(){
console.log('server running on http://'+host+':'+port);
})

在上面的代码中,我的节点服务器在 127.0.0.1:9001 中给它 运行s 消息,但是当我在浏览器中 运行 它时,我面对 "error 404 file not found",它不是我提到的错误。此外,我在此脚本文件的同一文件夹中有 index.html 文件。我的代码有什么问题?

实际上你的代码工作正常,

您可以更改您的 404

  res.writeHead(404, {"Content-Type": "text/plain"});
  res.end("sorry we could not find the file you requested");

另请参阅我们已将响应类型设置为 'text/html'

http://nodejs.org/api/http.html#http_class_http_serverresponse

你的代码对我来说工作得很好。 您应该在执行 server.js 文件的同一文件夹中有 index.htm 文件。

改变if条件

index.html != index.htm