簡體   English   中英

Node.js http 服務器 + 圖像

[英]Node.js http server + image

因此,我正在使用 Node.js 創建一個網站,並且正在使用 http 服務器。 我正在嘗試用它來提供圖像。 圖像肯定會顯示出來,但只是最上面的部分。 這是圖像、發生了什么以及服務器代碼(按此順序)。 在此處輸入圖像描述

在此處輸入圖像描述

const server = http.createServer((req, res) => {
// get the file path from req.url, or '/public/index.html' if req.url is '/'
const filePath = ( req.url === '/' ) ? '/public/index.html' : req.url;

// determine the contentType by the file extension
const extname = path.extname(filePath);
let contentType = 'text/html';
if (extname === '.js') contentType = 'text/javascript';
else if (extname === '.css') contentType = 'text/css';
else if(extname === (".png")) {
    var imagePath = path.join(__dirname, '/', req.url);
    var fileStream = fs.createReadStream(imagePath);
    res.writeHead(200, {"Content-Type": "image/png"});
    fileStream.pipe(res);
}

// pipe the proper file to the res object
res.writeHead(200, { 'Content-Type': contentType });
fs.createReadStream(`${__dirname}/${filePath}`, 'utf8').pipe(res);
});

另外,如果有幫助,我正在使用 websocket。

如果您的圖像是 PNG,那么您嘗試調用res.writeHead(...)兩次並嘗試調用 .pipe .pipe(res)兩次。 那肯定會出問題。

對於png文件,您似乎不需要.pipe()的完整路徑,並且可以這樣做:

const server = http.createServer((req, res) => {
    // get the file path from req.url, or '/public/index.html' if req.url is '/'
    const filePath = (req.url === '/') ? '/public/index.html' : req.url;

    // determine the contentType by the file extension
    const extname = path.extname(filePath);
    let contentType = 'text/html';
    if (extname === '.js') {
        contentType = 'text/javascript';
    } else if (extname === '.css') {
        contentType = 'text/css';
    } else if (extname === (".png")) {
        contentType = 'image/png';
    }

    // pipe the proper file to the res object
    res.writeHead(200, { 'Content-Type': contentType });
    fs.createReadStream(`${__dirname}/public/${filePath}`).pipe(res);
});

另外,請注意您的代碼存在嚴重的安全漏洞(我已在上面的代碼示例中對其進行了修補)。 您的代碼允許攻擊者讀取您的__dirname目錄中的任何文件(包括所有服務器文件),只需將該文件附加到 URL 即可。 你永遠不應該允許這樣做。 通過將 URL 與這樣的文件名匹配來查找的公共服務文件只能從僅用於公開可用文件的目錄中提供。 通常,人們會創建一個public目錄並僅從該目錄層次結構中提供文件。 請注意,我從這里更改了代碼:

${__dirname}/${filePath}

對此:

${__dirname}/public/${filePath}

並且,您需要將打算與此代碼匹配的公開可用文件移動到該子目錄中,並確保該子目錄僅包含對公眾免費可用的文件。


另請注意,用於在 nodejs 中創建 web 服務器的非常簡單的 Express 框架具有express.static() ,它已經為您完成了所有這些工作。 您只需創建一個公開可用文件(任何常見文件類型)的目錄,在 Express 設置中放置一行指向該文件目錄的中間件,當 URL 請求匹配文件名的葉子部分。 它會自動處理內容類型設置,自動查找index.html/請求,自動剝離來自 URL 的..請求等,並且針對安全問題進行了仔細檢查。

除了學習/學術原因,大多數人不會在 nodejs 中從頭開始制作 web,而是從非常有用且簡單的框架之一開始,例如 Express 或 nextjs,因為它們具有預先構建、預先測試的代碼您想在 web 服務器中執行的許多簡單操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM