node.js原生http模块写一个基本的web服务器

29 篇文章 0 订阅
8 篇文章 0 订阅
// 引入http模块
const http = require('http')
// // 导入 fs 文件系统模块
const fs = require('fs')
//导入 path 路径处理模块
const path = require('path')
// --------------引入结束-------------//
const server = http.createServer()
server.on('request', function (req, res) {
  // 设置请求头及默认404页面//
  let content = '<h4>404 Not Found</h4>'
  let dataStr = null
  res.setHeader('Content-Type', 'text/html; charset=utf-8')
  //-----设置结束-----//
  const url = req.url //当前请求的URL地址

  // 把请求的 url 地址,映射为本地文件的存放路径  
  var fpath = path.join(__dirname, url)
  console.log(url);
  if (url === '/' || url.indexOf('index.') !== -1) { //判断路径
    content = '<h4>首页</h4>'
    res.end(content)

  } else if (url.indexOf('/ablout') !== -1) {//判断路径
    content = '<h4>关于我们</h4>'
    res.end(content)
  } else if (url.indexOf('/clock') !== -1) {//判断路径
    // 4.1 根据映射过来的文件路径读取文件
    fpath = fpath + '.html'
    fs.readFile(fpath, 'utf8', (err, dataStr) => {
      // 4.2 读取文件失败后,向客户端响应固定的 "错误消息"  
      if (err) return res.end('404 Not Fount')
      // 4.3 读取文件成功后,将 "读取成功的内容" 响应给客户端 
      res.end(dataStr)
    })
  }
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值