【问题标题】:node.js 404 file not found errornode.js 404 文件未找到错误
【发布时间】:2015-11-21 13:28:41
【问题描述】:
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 中运行的消息,但是当我在浏览器中运行它时,我遇到了“找不到错误 404 文件”,这不是我提到的错误。我也在这个脚本文件的同一个文件夹中有 index.html 文件。我的代码有什么问题?

【问题讨论】:

    标签: node.js http-status-code-404 couchbase-nodejs-sdk


    【解决方案1】:

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

    您可以更改您的 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

    【讨论】:

    • 感谢您的建议,但我不知道为什么它没有读取我的静态 index.html 文件。
    【解决方案2】:

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

    更改 if 条件

    index.html != index.htm
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 2022-08-21
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      相关资源
      最近更新 更多