簡體   English   中英

如何設置nodejs服務器,通過檢查URL為客戶端提供正確的文件?

[英]How do I set up a nodejs server that gives the client the correct file by checking the url?

我正在嘗試編寫節點js服務器,如果資源在文件系統中,則返回用戶請求的任何內容。

例如,如果請求URL是/index.html ,它將嘗試在根目錄中找到名為“index.html”的文件,並使用該文件的流進行響應。 如果請求是/myscript.js ,它會做同樣的事情,找到一個名為myscript.js的文件並將其傳遞給響應。

這是我到目前為止:

var http = require("http");
var fs = require("fs");
var port = process.env.PORT || 3000;
http.createServer(function (request, response) {
    if (request.method == "GET") {
        console.log(request.url);
        if (request.url == "/") { // if the url is "/", respond with the home page
            response.writeHead(200, {"Content-Type": "text/html"});
            fs.createReadStream("index.html").pipe(response);
        } else if (fs.existsSync("." + request.url)) {
            response.writeHead(200/*, {"Content-Type": request.headers['content-type']}*/);
            fs.createReadStream("." + request.url).pipe(response);
        } else {
            response.writeHead(404, {"Content-Type": "text/plain"});
            response.end("404 Not Found");
        }
    } else {
        response.writeHead(404, {"Content-Type": "text/plain"});
        response.end("404 Not Found");
    }
}).listen(port);

// Console will print the message
console.log('Server running at http://127.0.0.1:' + port +'/');

關於這段代碼我有一些不喜歡的事情:

  • 顯然fs認為每當路徑以/開頭時,文件就不存在,所以我必須添加一個. 在文件路徑之前。 見第10和第12行。這總是有效嗎? 我覺得這是解決這個問題的一個非常糟糕的伎倆。
  • 我不知道所請求文件的內容類型(第11行)。 我在網上搜索並發現很多方法可以使用我必須使用npm安裝的其他模塊。 節點中是否有東西可以找出內容類型?

解決你的兩個要點:

  • 你需要一個有意義的. 使用fs因為fs會查看系統的根目錄。 請記住,系統根目錄與服務器根目錄不同。
  • 一個想法是使用path.extname然后使用switch語句來設置內容類型。

下面的代碼來自我寫的關於如何使用Node而不是Express設置簡單靜態服務器的博客文章

let filePath = `.${request.url}`; // ./path/to/file.ext
let ext = path.extname(filePath); // .ext
let contentType = 'application/octet-stream'; // default content type

if(ext === '') {

    filePath = './index.html'; // serve index.html
    ext = '.html';
}

switch (ext) {

    case '.html':
        contentType = 'text/html';
        break;

    case '.css':
        contentType = 'text/css';
        break;

    case 'js':
        contentType = 'text/javascript';
}

暫無
暫無

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

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