Node.js:http模块学习

117 阅读1分钟

一、http 模块-创建 Web 服务

需求1:创建 Web 服务并响应内容给浏览器 步骤:

  1. 加载 http 模块,创建 Web 服务对象
  2. 监听 request 请求事件,设置响应头和响应体
  3. 配置端口号并启动 Web 服务
  4. 浏览器请求 http://localhost:3000 测试 (localhost:固定代表本机的域名)
const http = require('http')
const server = http.createServer()
// 1.2 监听 request 请求事件,设置响应头和响应体
server.on('request', (req, res) => {
  // 设置响应头-内容类型-普通文本以及中文编码格式
  res.setHeader('Content-Type', 'text/plain;charset=utf-8')
  // 设置响应体内容,结束本次请求与响应
  res.end('欢迎使用 Node.js 和 http 模块创建的 Web 服务')
})
// 1.3 配置端口号并启动 Web 服务
server.listen(3000, () => {
  console.log('Web 服务启动成功了')
})

需求2:基于 Web 服务,开发提供网页资源的功能

步骤:

  1. 基于 http 模块,创建 Web 服务
  2. 使用 req.url 获取请求资源路径,并读取 index.html 里字符串内容返回给请求方
  3. 其他路径,暂时返回不存在提示
  4. 运行 Web 服务,用浏览器发起请求
const path = require('path')
// 1. 基于 http 模块,创建 Web 服务
const http = require('http')
const server = http.createServer()
server.on('request', (req, res) => {
  // 2. 使用 req.url 获取请求资源路径,并读取 index.html 里字符串内容返回给请求方
  if (req.url === '/index.html') {
    fs.readFile(path.join(__dirname, 'dist/index.html'), (err, data) => {
      if(err) console.log(err)
      else{
      res.setHeader('Content-Type', 'text/html;charset=utf-8')
      res.end(data.toString())
      }
    })
  } else {
    // 3. 其他路径,暂时返回不存在提示
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    res.end('你要访问的资源路径不存在')
  }
})
server.listen(8080, () => {
  console.log('Web 服务启动成功了')
})