将 CSS 链接到 HTML for nodejs server



我正在尝试使用 nodejs 将样式.css文件链接到hello.html页面以显示在本地主机中。但是输出仅以 html 格式格式化,并且不显示 css 样式。

这是我的代码!

项目.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); 

你好.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 文件。 节点.js在一个请求中提供多个文件 代码:

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

你可以试试这个!

var http = require('http')
var fs = require('fs')
http.createServer(function (req, res) {
let route = req.url.replace('/', '')
let request_url = route === '' || route === '/' ? 'hello.html' : route
console.log(request_url)
fs.exists(request_url, (exist) => {
if (Boolean(exist) === false) {
res.writeHead(404, {'content-type': 'text/html'})
res.end('Page Not Found')
return null
}
fs.readFile(request_url, function (err, data) {
res.writeHead(200)
res.write(data)
res.end()
})
})
}).listen(8080)

最新更新