在node基础上轻松三步搭建一个简单的web服务器,搞清除服务器中静态资源和动态资源(接口)的区别及如何处理请求

静态资源

  • 它们一般表现为一个一个的文件。例如index.html, style.css, index.js, mp4, .png....。

  • 处理请求静态资源时,服务器一般就直接读出资源的内容,再返回给客户端浏览器

 动态资源:接口

  • 它们不是以某个具体的文件存在的,而是服务器上的一段代码,访问接口时,服务器会执行这段代码,然后把代码的执行结果返回给客户端浏览器。

利用静态服务器批量处理请求

//引入模块
const http = require('http')
const fs = require('fs')
const path = require('path')
    // 策略模式
    // .png --> 'image/png'
    // .html --> 'text/html;charset=utf8'
    // .js --> 'application/javascript;charset=utf8'
    // .css --> 'text/css;charset=utf8'
let obj = {
  '.html': 'text/html;charset=utf8',
  '.css': 'text/css;charset=utf8',
  '.js': 'application/javascript;charset=utf8',
  '.png': 'image/png',
  '.json': 'application/json;charset=utf-8',
}
// 创建服务器
const server = http.createServer((req, res) => {
  // 利用三元表达式判断req.url的值
  const url = req.url === '/' ? 'index.html' : req.url
  //拼接地址
  const filePath = path.join(__dirname, 'public', url)
  //console.log(ext);
  fs.readFile(filePath, (err, data) => {
    if (err) {
      // 设置状态码
      res.statusCode = 404
      // 设置响应体,结束请求
      res.end('not found')
    } else {
        // 获取后缀名
      let ext = path.extname(filePath)
      if (obj[ext]) {
        // 设置响应头
            // if(extName === '.png') {
            //     res.setHeader('content-type', 'image/png')
            // } else if(extName === '.html') {
            //     res.setHeader('content-type', 'text/html;charset=utf8')
            // }else if(extName === '.js') {
            //     res.setHeader('content-type', 'application/javascript;charset=utf8')
            // }else if(extName === '.css') {
            //     res.setHeader('content-type', 'text/css;charset=utf8')
            // }
        res.setHeader('content-type', obj[ext])
      }
      // 设置响应体,结束请求
      res.end(data)
    }
  })
})
// 启动服务器
server.listen(8083, function () {
  console.log('服务器已启动,端口号为8083');
})

 以get类型为例提供一个名为/getList 的服务器接口

// 引入模块
const http = require('http')
const fs = require('fs')
const path = require('path')
// 创建服务器
const server = http.createServer((req, res) => {
  // 拼接地址
  let filePath = path.join(__dirname, 'json', 'data.json')
  //console.log(filePath);
  // if判断请求地址(接口)是否为'/getlist'且请求方式是否为“GET”
  if (req.url === '/getlist' && req.method === 'GET') {
    fs.readFile(filePath, (err, data) => {
      res.setHeader('content-type', 'application/json;charset=utf8')
      // 设置响应体,结束请求
      res.end(data)
    })
  } else {
    res.end('error')
  }
})

// 开启服务器
server.listen(8080, function () {
  console.log('端口为8080的服务器已开启');
})

 以get类型为例提供一个名为/someword 的服务器接口,使得有50%的可能返回one.json里的内容,50%可能返回two.json里的内容

// 引入核心模块
const http = require('http')
const path = require('path')
const fs = require('fs')
let filepath
// 创建服务器
const server = http.createServer((req, res) => {
  // let random = Math.floor(Math.random())
  // console.log(random);
  // 通过修改路径,使得当Math.random()>0.5时,读取one.json里的内容,<0.5时two.json里的内容
  if (Math.random() > 0.5) {
    filepath = path.join(__dirname, 'json', 'one.json')
  } else {
    filepath = path.join(__dirname, 'json', 'two.json')
  }
  // if判断请求地址(接口)是否为'/someword'且请求方式是否为“GET”
  if (req.url === '/someword' && req.method === 'GET') {
    fs.readFile(filepath, (err, data) => {
      res.setHeader('content-type', 'application/json;charset=utf8')
      res.end(data)
    })
  } else {
    res.statusCode = 404
    res.end('not found')
  }
})
// 开启服务器
server.listen(8081, function () {
  console.log('服务器已开启');
})

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值