鍍金池/ 問答/HTML/ Node.js創(chuàng)建的http服務(wù)器無法加載字體文件資源(font awesome

Node.js創(chuàng)建的http服務(wù)器無法加載字體文件資源(font awesome)

如圖所示,http服務(wù)器啟動后,source面板里面沒有font資源,請求字體文件404錯誤
這個是《Node.js實戰(zhàn)》里面的例題,稍微改動了一下...初學(xué)node...求指點..
報錯截圖

目錄結(jié)構(gòu)

// server.js
var http = require("http"),
    fs = require("fs"),
    path = require("path"),
    mime = require("mime"),
    cache = {};     // 用來緩存文件內(nèi)容(訪問內(nèi)存比訪問文件系統(tǒng)要快)

// 發(fā)送404錯誤
function send404(res) {
    res.writeHead(404, {
        "Content-Type": "text/html"
    });

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

// 發(fā)送文件
function sendFile(res, filepath, filecontent) {
    // console.log(mime.getType(path.basename(filepath))); // text/html
    res.writeHead(200, {
       "Content-Type": mime.getType(path.basename(filepath))    // 轉(zhuǎn)換成mime類型
    });

    res.end(filecontent);
}

// 提供靜態(tài)文件服務(wù)
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;  // 緩存文件內(nèi)容(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("服務(wù)器在本地3000端口啟動");
});
回答
編輯回答
孤星

服務(wù)器打印日志看看有沒有收到字體文件的請求

2018年5月21日 00:09
編輯回答
爛人

請問關(guān)于不能識別字體圖標(biāo) 或者說文件后面有版本號,你是怎么解決的

2018年4月11日 15:52
編輯回答
寫榮
fs.readFile(filepath, function (err, data) {
  // 這里的filepath,讀取字體文件時,是帶版本號的,
  // 即 ?v=4.7.0
  // fs 讀取時找不到對應(yīng)文件
}

自己在處理時,要考慮的因素很多;
可以參考已有的解決方案,例如:https://github.com/pillarjs/send 這個模塊。

2018年9月9日 08:56