简体   繁体   中英

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);
})

In the above code my node server is giving message its runs in 127.0.0.1:9001, but when I run it in my browser I face "error 404 file not found", which is not the error I mentioned. Also I have index.html file inside the same folder of this script file. What's wrong with my code?

Actually your code work fine,

you may change your 404

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

Also see we have set the response type to 'text/html'

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

在此处输入图片说明

You code works fine for me. You should have index.htm file in the same folder you execute the server.js file.

Change the if condition

index.html != index.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM