node js 怎么响应多个html页面
时间: 2023-06-15 12:08:15 浏览: 56
在 Node.js 中响应多个 HTML 页面,可以使用如下方法:
1. 使用 Express 框架:Express 是 Node.js 的一个流行的 Web 框架,它可以轻松地处理 HTTP 请求和响应。可以使用 Express 的路由功能来为不同的 URL 路径提供不同的响应。例如:
```javascript
const express = require('express');
const app = express();
// 响应 index.html
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// 响应 about.html
app.get('/about', (req, res) => {
res.sendFile(__dirname + '/about.html');
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
```
2. 使用 http 模块:Node.js 的内置 http 模块可以用来创建 HTTP 服务器。可以使用该模块的 request 和 response 对象来处理 HTTP 请求和响应。例如:
```javascript
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
if (req.url === '/') {
fs.readFile(__dirname + '/index.html', (err, data) => {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
res.end();
});
} else if (req.url === '/about') {
fs.readFile(__dirname + '/about.html', (err, data) => {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
res.end();
});
} else {
res.writeHead(404);
res.end('Page not found');
}
});
server.listen(3000, () => {
console.log('Server started on port 3000');
});
```
以上代码演示了如何使用 http 模块创建一个 HTTP 服务器,并根据不同的 URL 路径响应不同的 HTML 页面。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)