我正在尝试将 styles.css 文件链接到 hello.html 页面以显示在使用 Node.js 的本地主机。但输出仅采用 html 格式,并且不显示 css 样式。
这是我的代码!
project.js
var http = require('http');
var fs = require('fs');
http.createServer(function (req,res){
fs.readFile('hello.html',function(err,data){
res.writeHead(200,{'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8080);
hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="heading">
<h1>FILE UPLOADING!</h1>
</div>
<form method= "POST" enctype="multipart/form-data" action="fileupload">
<input type="file" name="filetoupload">
<input type="submit" id='bt' value="Submit">
</form>
</body>
</html>
样式.css
#heading{
color:green;
font-family: sans-serif,serif;
}
#bt{
background-color: #4CAF50;
color: #ffffff;
border-color: #4CAF50;
}
最佳答案
您可以从下面的链接中获取引用,您还必须使用 http 来提供您的 css 文件。 Node.js serve multiple files in one request代码:
var http = require('http');
var fs = require('fs');
http.createServer(function (req,res){
if(req.url === '/hello.html') {
fs.readFile('hello.html',function(err,data){
res.writeHead(200,{'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}
else if(req.url === '/style.css') {
fs.readFile('style.css',function(err,data){
res.writeHead(200,{"Content-Type": "text/css"});
res.write(data);
res.end();
});
}
}).listen(8080);
关于javascript - 将 CSS 链接到 Nodejs 服务器的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44943676/