node入門之實現(xiàn)頁面的curd

首先起一個node 服務 serve.js

http.createServer(function (req, res) {
// 將來做一些后臺邏輯處理 
}).listen(3000, () => {
  console.log('listening 3000')
});

然后新建基本頁面前端頁面用于交互 index.html 這里使用了 bootstrap的樣式

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
//此處路徑將css文件放于相同文件下 不然會找不到文件
    <link rel="stylesheet" type="text/css" href="./node_modules/bootstrap/dist/css/bootstrap.css">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2 row" style="margin-top: 30px;margin-bottom: 30px;">
            <div class="col-md-5 ">
                <label for="username">用戶名</label>
                <label>
                    <input type="text" id="username"/>
                </label>
            </div>
            <div class="col-md-5">
                <label for="password">密碼</label>
                <label>
                    <input type="password" id="password"/>
                </label>
            </div>
            <div class="col-md-2">
                <button class="btn btn-primary btn-sm add">添加</button>
            </div>
        </div>
        <ul class="list-group col-md-8">
        </ul>
    </div>
</div>
</body>
</html>

接著需要在serve.js中添加靜態(tài)頁面的訪問邏輯

http.createServer(function (req, res) {
// 將來做一些后臺邏輯處理 
 //處理靜態(tài)頁面
  fs.stat('.' + pathname, function (err, stats) {
    if (err) {
      res.statusCode = 404;
      res.end(`${pathname} not fount`)
    } else if (stats.isFile()) {
      res.setHeader('Content-Type', mime.getType() + ';charset=utf8');
      fs.createReadStream('.' + pathname).pipe(res)
    } else if (stats.isDirectory()) {
      res.setHeader('Content-Type', 'text/html;charset=utf8');
      let p = path.join('.' + pathname, './index.html');
      fs.createReadStream(p).pipe(res)
    }

  })
}).listen(3000, () => {
  console.log('listening 3000')
});

接著需要在serve.js中添加按符合resful的風格添加相應的接口

let http = require('http');
let fs = require('fs');
let url = require('url');
let path = require('path');
let mime = require('mime');
let user = [
  {
    id: 1, username: 'ywh', password: '你好123124'
  }, {
    id: 2, username: 'ywh2', password: '123456'
  }];


http.createServer(function (req, res) {
  let {pathname, query} = url.parse(req.url, true);
  //處理后臺
  if (pathname === '/user') {
    let id = query.id;
    switch (req.method) {
      case 'GET':
        if (!id) {
          res.setHeader("Content-Type", 'application/json;charset=utf-8');
          res.end(JSON.stringify(user))
        }
        break;
      case 'POST':
        let str = '';
        req.on('data', function (chunk) {
          str += chunk
        });
        req.on('end', function () {
          let user1 = JSON.parse(str);
          user1.id = user.length ? user[user.length - 1].id + 1 : 1;
          user.push(user1);
          res.end(JSON.stringify(user1));
        });
        break;
      case 'DELETE':
        if (id) {
          // 這里使用!=是由于前端傳過來的數(shù)據(jù)是一個json
          user = user.filter(item => item.id != id
          )
          ;
          res.end(JSON.stringify({}));
        }
        break;
      case 'PUT':
        break;
    }
    return
  }
  //處理靜態(tài)頁面
  fs.stat('.' + pathname, function (err, stats) {
    if (err) {
      res.statusCode = 404;
      res.end(`${pathname} not fount`)
    } else if (stats.isFile()) {
      res.setHeader('Content-Type', mime.getType() + ';charset=utf8');
      fs.createReadStream('.' + pathname).pipe(res)
    } else if (stats.isDirectory()) {
      res.setHeader('Content-Type', 'text/html;charset=utf8');
      let p = path.join('.' + pathname, './index.html');
      fs.createReadStream(p).pipe(res)
    }

  })
}).listen(3000, () => {
  console.log('listening 3000')
});

前端發(fā)起相應請求的方法(fetch)

<script>

  (function () {
    let oul = document.querySelector('.list-group');
    let username = document.getElementById('username');
    let password = document.getElementById('password');
    let add = document.querySelector('.add');
    let template = function (username, password, id) {
      return `<li class="list-group-item">用戶名:${username} 密碼:${password}
        <button class ='btn-danger btn-sm delete' style="float: right" data-id="${id}">
        刪除</button>
</li>`;
    };

    function render(data) {
      let str = '';
      data.forEach(item => {
        str += template(item.username, item.password, item.id);
      });
      oul.innerHTML = str;
    }

    // 查詢
    fetch('/user').then(res => {
      return res.json()
    }).then(data => {
      render(data)
    }).catch(err => {
      console.log(err)
    });

    // 添加用戶
    add.addEventListener('click', () => {
      fetch('/user', {
        method: "POST",
        body: JSON.stringify({username: username.value, password: password.value})
      }).then(res => {
        return res.json()
      }).then(data => {
        let oDiv = document.createElement('div');
        oDiv.innerHTML = template(data.username, data.password, data.id);
        oul.appendChild(oDiv.firstElementChild);
      }).catch(err => {
        console.log(err)
      })
    }, false);

    // 刪除
    oul.addEventListener('click', (e) => {
      if (e.target.tagName === 'BUTTON') {
        let id = e.target.dataset.id;
        fetch(`/user?id=${id}`, {
          method: "DELETE",
        }).then(res => {
          return res.json()
        }).then(data => {
          oul.removeChild(e.target.parentNode)
        }).catch(err => {
          console.log(err)
        })
      }
    }, false)
  })()
</script>

demo git地址

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1-------- 走進前端 2-------- jQuery 3-------- CSS 4-------- A...
    依依玖玥閱讀 2,354評論 0 34
  • 每日一得:訓練我們的思維,練習操控它們,并沒有乍看上去那么難(其實登上珠穆朗瑪峰也沒那么難)。那只需要訓練就可以。...
    我家有個皮特閱讀 267評論 0 0
  • 回首 那年銀杏葉飄落的季節(jié) 牽手在金黃的校園 銀杏樹下的承諾 記憶猶在 人已不在 漫天飄落的銀杏葉 也許是終結的預...
    貓貓小壞閱讀 433評論 0 1
  • Tomcat是一個 開源的Servlet 容器,實現(xiàn)了對 Servlet 和 JSP 的支持,它本身也內含了一個 ...
    _stefan__閱讀 1,905評論 0 1