简体   繁体   中英

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

Say you have a CSS file with the code:

body{
    margin:0px;
}

And the HTML file index.html. How could you create a server that takes index.html and adds the CSS? Edit:

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);

This stuff is a lot simpler with a simple framework like Express where you can configure it to automatically serve a directory of static files.

But, if you want to do it yourself using only the built-in http object, you can do something like this:

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);

Then, inside of index.html , you can have:

<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>

In styles.css , you can have:

.red {
    color: red;
}

That will cause the browser to request /styles.css and your web server will be configured to serve that file for that request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM