根据不同请求返回对应的页面

// 引入相关模块
const http = require('http');
const fs = require('fs');
const path = require('path');

//实例化一个服务器
const server = http.createServer();
//给服务器绑定request事件
server.on('request', (req, res) => {
  
  if (req.url.startsWith('/index') || req.url === '/') {
    fs.readFile(path.join(__dirname, '/page/index.html'), (err, data) => {
      if (err) {
        return console.log('文件读取失败');
      } else {
        res.end(data)
      }
    })
  }else if(req.url.startsWith('/list')){
    fs.readFile(path.join(__dirname, '/page/list.html'), (err, data) => {
      if (err) {
        return console.log('文件读取失败');
      } else {
        res.end(data)
      }
    })
  }else if(req.url.startsWith('/login')){
    fs.readFile(path.join(__dirname, '/page/login.html'), (err, data) => {
      if (err) {
        return console.log('文件读取失败');
      } else {
        res.end(data)
      }
    })
  }else{
    fs.readFile(path.join(__dirname, '/page/404.html'), (err, data) => {
      if (err) {
        return console.log('文件读取失败');
      } else {
        res.end(data)
      }
    })
  }
})
// 设置端口,启动服务器
server.listen(9999, () => {
  console.log('服务器开启');
})

那么问题来了,页面中请求的css文件,图片等静态资源如何处理?

posted @ 2020-10-06 22:33  MIKE-CHOW  阅读(143)  评论(0)    收藏  举报