当前位置:网站首页>node手写服务器实现访问index页面
node手写服务器实现访问index页面
2022-07-30 05:40:00 【星月前端】
node手写服务器实现访问index页面;
1.输入http://127.0.0.1/ 即可访问首页,
2.输入http://127.0.0.1/index 即可访问首页,
3.输入http://127.0.0.1/index.html 即可访问首页
4.输入其他路径会提示固定的“错误消息”
文件结构:

上代码:
// 1.1 导入 http 模块
const http = require('http')
// 1.2 导入 fs 模块
const fs = require('fs')
// 1.3 导入 path 模块
const path = require('path')
// 2.1 创建 web 服务器
const server = http.createServer()
// 2.2 监听 web 服务器的 request 事件
server.on('request', (req, res) => {
// 3.1 获取到客户端请求的 URL 地址
const url = req.url
// 3.2 把请求的 URL 地址映射为具体文件的存放路径
// 5.1 预定义一个空白的文件存放路径
let fpath = ''
if (url === '/') {
//输入http://127.0.0.1/ 即可访问首页
fpath = path.join(__dirname, './clock/index.html')
} else if (url === 'index') {
// 输入http://127.0.0.1/index 即可访问首页
fpath = path.join(__dirname, '/clock', url + '.html')
} else {
//输入http://127.0.0.1/index.html 即可访问首页
fpath = path.join(__dirname, './clock', url)
}
// 4.1 根据“映射”过来的文件路径读取文件的内容
fs.readFile(fpath, 'utf8', (err, dataStr) => {
// 4.2 读取文件失败,向客户端响应固定的“错误消息”
if (err) return res.end('404 Not found.')
// 4.3 读取成功,将读取成功的内容,响应给客户端
res.end(dataStr)
})
})
// 2.3 启动服务器
// cmd输入: node (文件名)
server.listen(80, () => {
console.log('server running at http://127.0.0.1')
})边栏推荐
猜你喜欢
随机推荐
Socket通信编程
Error: listen EADDRINUSE: address already in use 127.0.0.1:3000
[Other] DS5
技术人该访问的论坛
Frobenius norm(Frobenius 范数)
Numpy 中 np.vstack() 和 np.hstack() 简单解析
VS2022中关于scanf函数报错解决方法
Different usage scenarios of subqueries as retrieval tables and the question of whether to add aliases
optimizer.zero_grad()
[Koltin Flow (1)] Five ways to create flow
MySQL user authorization
Falling ants (Peking University entrance exam questions)
Pytorch to(device)
417.太平洋大西洋水流问题
SRA数据下载方法总结
C语言必会15个文件函数
flask-socketio实现的网页聊天室(一)
MySQL Soul 16 Questions, how many questions can you last?
EOF的用法——while(scanf(“%d“,&num)!=EOF)
MySQL 用户授权





![[详解C语言]一文带你玩转数组](/img/1b/245fdc7f3711cf794175da7a93b128.png)



