Node.js创建的http服务器无法加载字体文件资源(font awesome)

如图所示,http服务器启动后,source面板里面没有font资源,请求字体文件404错误
这个是《Node.js实战》里面的例题,稍微改动了一下...初学node...求指点..
报错截图

目录结构

// server.js
var http = require("http"),
    fs = require("fs"),
    path = require("path"),
    mime = require("mime"),
    cache = {};     // 用来缓存文件内容(访问内存比访问文件系统要快)

// 发送404错误
function send404(res) {
    res.writeHead(404, {
        "Content-Type": "text/html"
    });

    fs.readFile("public/404.html", function (err, data) {
        res.end(data);
    });
}

// 发送文件
function sendFile(res, filepath, filecontent) {
    // console.log(mime.getType(path.basename(filepath))); // text/html
    res.writeHead(200, {
       "Content-Type": mime.getType(path.basename(filepath))    // 转换成mime类型
    });

    res.end(filecontent);
}

// 提供静态文件服务
function serveStatic(res, cache, filepath) {
    if (cache[filepath]){   // 文件在缓存中
        sendFile(res, filepath, cache[filepath]);
    }else {     // 文件不在缓存中
        fs.readFile(filepath, function (err, data) {
           if (err){
               send404(res);
           }else {
               sendFile(res, filepath, data);
               cache[filepath] = data;  // 缓存文件内容(Buffer类型)
           }
        });
    }
    // console.log(cache);
}

var server = http.createServer(function (req, res) {
    var filepath = null;
    // console.log(req.url);   // /......
    if (req.url == "/"){
        filepath = "public/index.html";
    }else {
        filepath = "public" + req.url;
    }

    serveStatic(res, cache, filepath);
}).listen(3000, function () {
    console.log("服务器在本地3000端口启动");
});
阅读 4.7k
3 个回答
fs.readFile(filepath, function (err, data) {
  // 这里的filepath,读取字体文件时,是带版本号的,
  // 即 ?v=4.7.0
  // fs 读取时找不到对应文件
}

自己在处理时,要考虑的因素很多;
可以参考已有的解决方案,例如:https://github.com/pillarjs/send 这个模块。

服务器打印日志看看有没有收到字体文件的请求

新手上路,请多包涵

请问关于不能识别字体图标 或者说文件后面有版本号,你是怎么解决的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题