使用nodejs技术搭建服务器并返回html页面
要使用Node.js构建服务器并返回HTML页面,您可以按照以下步骤进行操作:
- 在您的项目文件夹中创建一个新的文件夹,例如"server"。
- 在"server"文件夹中创建一个新的JavaScript文件,例如"app.js"。
- 在"app.js"文件中,导入所需的模块:
const http = require('http');
const fs = require('fs');
- 创建一个HTTP服务器并指定请求处理逻辑:
const server = http.createServer((req, res) => {
if (req.url === '/') {
// 读取HTML文件内容
fs.readFile('./index.html', 'utf8', (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
- 启动服务器并监听指定的端口:
const port = 3000;
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
- 在项目文件夹中创建一个新的HTML文件,例如"index.html",并将所需的内容添加到该文件中。
现在,您可以通过运行node server/app.js命令来启动服务器,并在浏览器中访问http://localhost:3000来查看返回的HTML页面
原文地址: http://www.cveoy.top/t/topic/iFhK 著作权归作者所有。请勿转载和采集!