如何将CSS导入node.js服务器?
假设您有一个带有代码的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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用简单的框架(例如Express),您可以在其中配置它以自动提供静态文件目录。
但是,如果您只想使用内置的HTTP对象自己进行操作,则可以做类似的事情:
然后,在
index.html
的内部,您可以拥有:in
样式。 CSS
,您可以拥有:这将导致浏览器请求
/styles.css
,并且您的Web服务器将配置为为该请求提供该文件。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:
Then, inside of
index.html
, you can have:In
styles.css
, you can have:That will cause the browser to request
/styles.css
and your web server will be configured to serve that file for that request.