[英]How can you import CSS into a node.js server?
Say you have a CSS file with the code:假设您有一个带有代码的 CSS 文件:
body{
margin:0px;
}
And the HTML file index.html.以及 HTML 文件 index.html。 How could you create a server that takes index.html and adds the CSS?
您如何创建一个接受 index.html 并添加 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.使用像 Express 这样的简单框架,这些东西要简单得多,您可以将其配置为自动提供静态文件目录。
But, if you want to do it yourself using only the built-in http object, you can do something like this:但是,如果你想自己使用内置的 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);
Then, inside of index.html
, you can have:然后,在
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>
In styles.css
, you can have:在
styles.css
,您可以拥有:
.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.这将导致浏览器请求
/styles.css
并且您的 Web 服务器将被配置为为该请求提供该文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.