使用HTTP模块搭建服务器

使用HTTP模块搭建服务器

// 导入http模块
const http = require('http')

// 创建web服务实例对象
const server = http.createServer()



// // 为server绑定request事件,监听客户端的请求
server.on('request',(req, res)=>{
// 获取url地址
const url = req.url;
// 设置默认内容为404 Not Found
let content = '404 Not Found!';
// 判断用户请求是否为 / 或者/index.html 首页

if(url === '/' || url === '/index.html'){
    content = '<h1>首页</h1>';
// 判断用户请求是否为about.html 关于页面
} else if(url === '/about.html'){
    content = '<h1>关于页面</h1>';
}

// 调用res.setHeader()方法,设置Content-type响应头,为了防止中文乱码
res.setHeader('Content-type','text/html; charset=utf-8')

// 使用res.end()把内容响应给客户端
res.end(content)
})


// 启动服务器
// 端口号如果是80则可以省略不写,其他的必须写
server.listen(80,()=>{
    console.log('Server running at http://127.0.0.1');
})

// 打开终端后 CTRL+鼠标左键点击http://127.0.0.1 即可打开网址

实现clock时钟的web服务器


// 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 地址
  //     /clock/index.html
  //     /clock/index.css
  //     /clock/index.js
  const url = req.url
  // 3.2 把请求的 URL 地址映射为具体文件的存放路径
  // const fpath = path.join(__dirname, url)
  // 5.1 预定义一个空白的文件存放路径
  let fpath = ''
  if (url === '/') {
    fpath = path.join(__dirname, './clock/index.html')
  } else {
    //     /index.html
    //     /index.css
    //     /index.js
    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 启动服务器
server.listen(80, () => {
  console.log('server running at http://127.0.0.1')
})

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容