请用Node.js代码写一段网页,html文件和css文件在同一个文件夹‘www’中,而Node.js文件与'www'文件夹在同一目录中。请把Node.js代码,html代码和css代码告诉我
时间: 2023-03-29 07:00:46 浏览: 73
以下是Node.js代码:
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
const filePath = path.join(__dirname, 'www', req.url === '/' ? 'index.html' : req.url);
const extname = path.extname(filePath);
let contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
}
fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code === 'ENOENT') {
fs.readFile(path.join(__dirname, 'www', '404.html'), (err, content) => {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end(content, 'utf8');
});
} else {
res.writeHead(500);
res.end(`Server Error: ${err.code}`);
}
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf8');
}
});
});
const PORT = process.env.PORT || 500;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
以下是HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Welcome to my website!</h1>
<p>This is a paragraph.</p>
<script src="script.js"></script>
</body>
</html>
以下是CSS代码:
body {
background-color: #f2f2f2;
}
h1 {
color: #333;
}
p {
font-size: 18px;
line-height: 1.5;
}
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)