• 【Node.js】路由


    基础使用

    写法一:

    // server.js
    const http  = require('http');
    const fs = require('fs');
    const route  = require('./route')
    http.createServer(function (req, res) {
      const myURL = new URL(req.url, 'http://127.0.0.1')
      route(res, myURL.pathname)
      res.end()
    }).listen(3000, ()=> {
      console.log("server start")
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    // route.js
    const fs = require('fs')
    function route(res, pathname) {
      switch (pathname) {
        case '/login':
          res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' })
          res.write(fs.readFileSync('./static/login.html'), 'utf-8')
          break;
        case '/home':
          res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' })
          res.write(fs.readFileSync('./static/home.html'), 'utf-8')
          break
        default:
          res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' })
          res.write(fs.readFileSync('./static/404.html'), 'utf-8')
          break
      }
    }
    module.exports = route
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    写法二:

    // route.js
    const fs = require('fs')
    
    const route = {
      "/login": (res) => {
        res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' })
        res.write(fs.readFileSync('./static/login.html'), 'utf-8')
      },
      "/home": (res) => {
        res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' })
        res.write(fs.readFileSync('./static/home.html'), 'utf-8')
      },
      "/404": (res) => {
        res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' })
        res.write(fs.readFileSync('./static/404.html'), 'utf-8')
      },
      "/favicon.ico": (res) => {
        res.writeHead(200, { 'Content-Type': 'image/x-icon;charset=utf-8' })
        res.write(fs.readFileSync('./static/favicon.ico'))
      }
    }
    module.exports = route
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    // server.js
    const http  = require('http');
    const fs = require('fs');
    const route  = require('./route')
    http.createServer(function (req, res) {
      const myURL = new URL(req.url, 'http://127.0.0.1')
      try {
        route[myURL.pathname](res)
      } catch (error) {
        route['/404'](res)
      }
      res.end()
    }).listen(3000, ()=> {
      console.log("server start")
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    注册路由

    // api.js
    function render(res, data, type = "") {
      res.writeHead(200, { 'Content-Type': `${type ? type : 'application/json'};charset=utf-8` })
      res.write(data)
      res.end()
    }
    const apiRouter = {
      'api/login':(res)=> [
        render(res, `{ok:1}`)
      ]
    }
    module.exports = apiRouter
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    // route.js
    const fs = require('fs')
    
    function render(res, path, type="") {
      res.writeHead(200, { 'Content-Type': `${type?type:'text/html'};charset=utf-8` })
      res.write(fs.readFileSync(path), 'utf-8')
      res.end()
    }
    
    const route = {
      "/login": (res) => {
        render(res, './static/login.html')
      },
      "/home": (res) => {
        render(res, './static/home.html')
      },
      "/404": (res) => {
        res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' })
        res.write(fs.readFileSync('./static/404.html'), 'utf-8')
        res.end()
      },
      "/favicon.ico": (res) => {
        render(res, './static/favicon.ico', 'image/x-icon')
      }
    }
    module.exports = route
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    // server.js
    const http = require('http');
    const Router = {}
    const use = (obj) => {
      Object.assign(Router, obj)
    }
    const start = () => {
      http.createServer(function (req, res) {
        const myURL = new URL(req.url, 'http://127.0.0.1')
        try {
          Router[myURL.pathname](res)
        } catch (error) {
          Router['/404'](res)
        }
    
      }).listen(3000, () => {
        console.log("server start")
      })
    }
    exports.start = start
    exports.use = use
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    // index.js
    const server = require('./server');
    const route = require('./route');
    const api = require('./api');
    // 注册路由
    server.use(route)
    server.use(api)
    server.start()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    get 和 post

    // api.js
    function render(res, data, type = "") {
      res.writeHead(200, { 'Content-Type': `${type ? type : 'application/json'};charset=utf-8` })
      res.write(data)
      res.end()
    }
    const apiRouter = {
      '/api/login': (req,res) => {
        const myURL = new URL(req.url, 'http:/127.0.0.1')
        if(myURL.searchParams.get('username') === 'admin' && myURL.searchParams.get('password') === '123456') {
          render(res, `{"ok":1)`)
        } else {
          render(res, `{"ok":0}`)
        }
      },
      '/api/loginpost': (req, res) => {
        let post = ''
        req.on('data', chunk => {
          post += chunk
    
        })
        req.on('end', () => {
          console.log(post)
          post = JSON.parse(post)
          if(post.username === 'admin' && post.password === '123456') {
            render(res, `{"ok":1}`)
          }else {
            render(res, `{"ok":0}`)
          }
        })
      }
    }
    module.exports = apiRouter
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    // route.js
    const fs = require('fs')
    
    function render(res, path, type="") {
      res.writeHead(200, { 'Content-Type': `${type?type:'text/html'};charset=utf-8` })
      res.write(fs.readFileSync(path), 'utf-8')
      res.end()
    }
    
    const route = {
      "/login": (req,res) => {
        render(res, './static/login.html')
      },
      "/home": (req,res) => {
        render(res, './static/home.html')
      },
      "/404": (req,res) => {
        res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' })
        res.write(fs.readFileSync('./static/404.html'), 'utf-8')
        res.end()
      },
      "/favicon.ico": (req,res) => {
        render(res, './static/favicon.ico', 'image/x-icon')
      }
    }
    module.exports = route
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    // server.js
    const http = require('http');
    const Router = {}
    const use = (obj) => {
      Object.assign(Router, obj)
    }
    const start = () => {
      http.createServer(function (req, res) {
        const myURL = new URL(req.url, 'http://127.0.0.1')
        try {
          Router[myURL.pathname](req, res)
        } catch (error) {
          Router['/404'](req, res)
        }
    
      }).listen(3000, () => {
        console.log("server start")
      })
    }
    exports.start = start
    exports.use = use
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    // index.js
    const server = require('./server');
    const route = require('./route');
    const api = require('./api');
    // 注册路由
    server.use(route)
    server.use(api)
    server.start()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    
    DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Documenttitle>
    head>
    
    <body>
      <div>
        用户名:<input type="text" class="username">
      div>
      <div>
        密码:<input type="password" class="password">
      div>
      <div>
        <button class="login">登录-getbutton>
        <button class="loginpost">登录-postbutton>
      div>
      <script>
        const ologin = document.querySelector('.login')
        const ologinpost = document.querySelector('.loginpost')
        const password = document.querySelector('.password')
        const username = document.querySelector('.username')
        // get 请求
        ologin.onclick = () => {
          // console.log(username.value, password.value)
          fetch(`/api/login?username=${username.value}&password=${password.value}`)
            .then(res => res.text())
            .then(res => {
              console.log(res)
            })
        }
        // post 请求
        ologinpost.onclick = () => {
          fetch('api/loginpost',{
            method: 'post',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              username: username.value,
              password: password.value
            })
          }).then(res => res.text())
            .then(res=> {
              console.log(res)
            })
        }
      script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55

    静态资源管理

    成为静态资源文件夹static,可以直接输入类似于login.html或者login进行访问(忽略static/)。

    在这里插入图片描述

    在这里插入图片描述

    
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Documenttitle>
      <link rel="stylesheet" href="/css/login.css">
    head>
    
    <body>
      <div>
        用户名:<input type="text" class="username">
      div>
      <div>
        密码:<input type="password" class="password">
      div>
      <div>
        <button class="login">登录-getbutton>
        <button class="loginpost">登录-postbutton>
      div>
      <script src="/js/login.js">script>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    /* login.css */
    div {
      background-color: pink;
    }
    
    • 1
    • 2
    • 3
    • 4
    // login.js
    const ologin = document.querySelector('.login')
    const ologinpost = document.querySelector('.loginpost')
    const password = document.querySelector('.password')
    const username = document.querySelector('.username')
    // get 请求
    ologin.onclick = () => {
      // console.log(username.value, password.value)
      fetch(`/api/login?username=${username.value}&password=${password.value}`)
        .then(res => res.text())
        .then(res => {
          console.log(res)
        })
    }
    // post 请求
    ologinpost.onclick = () => {
      fetch('api/loginpost', {
        method: 'post',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username: username.value,
          password: password.value
        })
      }).then(res => res.text())
        .then(res => {
          console.log(res)
        })
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    // api.js
    function render(res, data, type = "") {
      res.writeHead(200, { 'Content-Type': `${type ? type : 'application/json'};charset=utf-8` })
      res.write(data)
      res.end()
    }
    const apiRouter = {
      '/api/login': (req, res) => {
        const myURL = new URL(req.url, 'http:/127.0.0.1')
        if (myURL.searchParams.get('username') === 'admin' && myURL.searchParams.get('password') === '123456') {
          render(res, `{"ok":1)`)
        } else {
          render(res, `{"ok":0}`)
        }
      },
      '/api/loginpost': (req, res) => {
        let post = ''
        req.on('data', chunk => {
          post += chunk
    
        })
        req.on('end', () => {
          console.log(post)
          post = JSON.parse(post)
          if (post.username === 'admin' && post.password === '123456') {
            render(res, `{"ok":1}`)
          } else {
            render(res, `{"ok":0}`)
          }
        })
      }
    }
    module.exports = apiRouter
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    // index.js
    const server = require('./server');
    const route = require('./route');
    const api = require('./api');
    // 注册路由
    server.use(route)
    server.use(api)
    server.start()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    // route.js
    const fs = require('fs')
    const mime = require('mime')
    const path = require('path')
    function render(res, path, type = "") {
      res.writeHead(200, { 'Content-Type': `${type ? type : 'text/html'};charset=utf-8` })
      res.write(fs.readFileSync(path), 'utf-8')
      res.end()
    }
    
    const route = {
      "/login": (req, res) => {
        render(res, './static/login.html')
      },
      "/": (req, res) => {
        render(res, './static/home.html')
      },
      "/home": (req, res) => {
        render(res, './static/home.html')
      },
      "/404": (req, res) => {
        // 校验静态资源能否读取
        if(readStaticFile(req, res)) {
          return 
        }
        res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' })
        res.write(fs.readFileSync('./static/404.html'), 'utf-8')
        res.end()
      },
      // 静态资源下没有必要写该 ico 文件加载
      // "/favicon.ico": (req, res) => {
      //   render(res, './static/favicon.ico', 'image/x-icon')
      // }
    }
    
    // 静态资源管理
    function readStaticFile(req, res) {
      const myURL = new URL(req.url, 'http://127.0.0.1:3000')
      // __dirname 获取当前文件夹的绝对路径  path 有以统一形式拼接路径的方法,拼接绝对路径
      const pathname = path.join(__dirname, '/static', myURL.pathname)
      if (myURL.pathname === '/') return false
      if (fs.existsSync(pathname)) {
        // 在此访问静态资源
        // mime 存在获取文件类型的方法
        // split 方法刚好截取文件类型
        render(res, pathname, mime.getType(myURL.pathname.split('.')[1]))
        return true
      } else {
        return false
      }
    }
    module.exports = route
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    // server.js
    const http = require('http');
    const Router = {}
    const use = (obj) => {
      Object.assign(Router, obj)
    }
    const start = () => {
      http.createServer(function (req, res) {
        const myURL = new URL(req.url, 'http://127.0.0.1')
        try {
          Router[myURL.pathname](req, res)
        } catch (error) {
          Router['/404'](req, res)
        }
    
      }).listen(3000, () => {
        console.log("server start")
      })
    }
    exports.start = start
    exports.use = use
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
  • 相关阅读:
    leetcode day05 A+B问题
    【Linux】基本指令(四)
    MES生产管理系统的五个关键组件
    C++中的继承(下)
    6. Queue
    Termius 8 for Mac(多协议服务器连接软件)
    支持Python的新版vTESTstudio测试用例编写方法大集合(上)
    Rflysim | 传感器标定与测量实验二
    第一章 数据可视化入门
    【工程应用六】 继续聊一聊高效率的模板匹配算法(分水岭助威+蒙版提速)。
  • 原文地址:https://blog.csdn.net/XiugongHao/article/details/133786071