簡體   English   中英

如何將 CSS 導入 node.js 服務器?

[英]How can you import CSS into a node.js server?

假設您有一個帶有代碼的 CSS 文件:

body{
    margin:0px;
}

以及 HTML 文件 index.html。 您如何創建一個接受 index.html 並添加 CSS 的服務器? 編輯:

var http = require('http');
var fs = require('fs');

function sendFile(res, filename, type) {
    fs.readFile(filename, function(err, data) {
        if (err) {
            console.log(err);
            res.statusCode = 404;
            res.end();
            return
                ;
        }
        res.writeHead(200, { 'Content-Type': type });
        res.write(data);
        res.end();
    });
}

http.createServer(function(req, res) {
    if (req.url == "/") {
        sendFile(res, "index.html", "text/html");
    } 
    else if (req.url == "/styles.css") {
        sendFile(res, "styles.css", "text/css");
    } 
    else {
        res.statusCode = 404;
        res.end();
    }
}).listen(8080);

使用像 Express 這樣的簡單框架,這些東西要簡單得多,您可以將其配置為自動提供靜態文件目錄。

但是,如果你想自己使用內置的 http 對象,你可以這樣做:

const http = require('http');
const fs = require('fs');

function sendFile(res, filename, type) {
    fs.readFile(filename, function(err, data) {
        if (err) {
            console.log(err);
            res.statusCode = 404;
            res.end();
            return;
        }
        res.writeHead(200, { 'Content-Type': type });
        res.write(data);
        res.end();
    });
}

http.createServer(function(req, res) {
    if (req.url === "/") {
        sendFile(res, "index.html", "text/html");
    } else if (req.url === "/styles.css") {
        sendFile(res, "styles.css", "text/css");
    } else {
        res.statusCode = 404;
        res.end();
    }
}).listen(8080);

然后,在index.html中,您可以擁有:

<html>
<head>
<link href="/styles.css"  rel="stylesheet">
</head>
<body>
    <div class="red">This is some text that is supposed to be red</div>
</body>
</html>

styles.css ,您可以擁有:

.red {
    color: red;
}

這將導致瀏覽器請求/styles.css並且您的 Web 服務器將被配置為為該請求提供該文件。

暫無
暫無

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

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