前言
前面已經學習了如何查詢資料並打印在前端畫面上,接下來就是將表單資料 post 之後新增到資料庫內
新增資料
接下來 ejs 表單部分要操作調整一下
1 2 3 4 5 6 7
| <form action="/post" method="post"> <input type="hidden" name="_csrf" value="<%= csrf %>"/> <input type="email" name="email" id="email"> <input type="text" name="firstname" id="firstname"> <input type="text" name="lastname" id="lastname"> <input type="submit" value="送出"> </form>
|
然後在來就要修改 post router,這邊會使用到的方法是 create
,所以程式碼就會像這樣子
1 2 3 4 5 6 7 8 9
| router.post('/post', csrfMD ,async (ctx, next) => { var modelDate = { firstName: ctx.request.body.firstname, lastName: ctx.request.body.lastname, createdAt: new Date(), }; await models.User.create(modelDate); await ctx.redirect('/'); })
|
當我們輸入表單
![輸入表單]()
送出之後就可以在資料庫看到資料新增上去了
![資料新增]()
修改資料
接下來就是修改資料,但是這邊我必須做一些 EJS 的調整,這樣子才可以跟後端說我要撈取哪一筆準備更新的資料
1 2 3 4 5
| <ul> <% for(item in user) {%> <li> ID:<%- user[item].dataValues.id%> / 姓名:<%- user[item].dataValues.firstName%> - <a href="/edit/<%- user[item].dataValues.id %>">編輯</a></a></li> <% } %> </ul>
|
由於我們要透過 edit/:id
來取得要更新的資料,所以就要在新增一個頁面以及 router,那 EJS 部分我就不提供了,因為很簡單,這邊就只講 router 部分
首先我們是透過 params 傳參數的方式,所以會使用到 ctx.params
的方法來取的參數
1 2 3 4 5 6 7
| router.get('/edit', csrfMD ,async (ctx, next) => { console.log(ctx.params.id) await ctx.render('edit', { title: '更新資料', csrf: ctx.csrf, }) })
|
![傳參數]()
那個接下來就要透過使用 sequelize 的 findOne()
來尋找資料哩
1 2 3 4 5
| models.User.findOne({ where: { id: ctx.params.id } }).then((result) => { console.log(result); })
|
那麼就可以得到我們要找的資料
![findOne]()
接下來就是將資料傳到欄位內,所以這邊的 router 最終就會變成這樣
1 2 3 4 5 6 7 8 9 10 11
| .get('/edit', csrfMD ,async (ctx, next) => { await models.User.findOne({ where: { id: ctx.params.id } }).then(async (result) => { await ctx.render('edit', { title: '更新資料', csrf: ctx.csrf, user: result.dataValue }) }) })
|
而 EJS 部分則會是這樣
1 2 3 4 5 6 7
| <form action="/post" method="post"> <input type="hidden" name="_csrf" value="<%= csrf %>"/> <input type="email" name="email" id="email" value="<%- user.email %>"> <input type="text" name="lastname" id="lastname" value="<%- user.lastName %>"> <input type="text" name="firstname" id="firstname" value="<%- user.firstName %>"> <input type="submit" value="送出"> </form>
|
拉出來的結果如下
![查詢結果]()
那麼我們這邊還需要新增一個 router 也就是 post
,是要接收更新的資料的
1 2 3 4 5 6 7 8 9 10 11 12 13
| router.post('/edit/:id', csrfMD, async (ctx, next) => { await models.User.update( { firstName: ctx.request.body.firstname, lastName: ctx.request.body.lastname, updatedAt: new Date(), }, { where: { id: ctx.params.id } }).then(async (result) => { await ctx.redirect('/'); }) })
|
接下來我們就直接來修改資料吧,原本資料是這樣
![資料新增]()
那我預計修改成這樣
![預計修改]()
當我們送出表單後,就可以看到資料更新哩~
![資料更新成功]()
刪除資料
接下來要講的是比較危險的動作,也就是資料刪除,這個動作如果一個不小心是會導致資料無法復原,所以在這邊通常建議一定要做二次提醒唷~
首先先新增一個 delete router,這邊會使用到 destroy
方法,由於一般都會透過 AJAX
1 2 3 4 5 6 7 8 9
| .delete('/delete/:id', csrfMD, async (ctx, next) => { await models.User.destroy( { where: { id: ctx.params.id } }).then(async (result) => { console.log('刪除成功'); await ctx.redirect('/'); }) })
|
那麼 EJS 部分就透過 AJAX 方式來傳送,所以 EJS 部分要稍微調整一下
1 2 3 4 5
| <ul id="content"> <% for(item in user) {%> <li> ID:<%- user[item].dataValues.id%> / 姓名:<%- user[item].dataValues.firstName%> - <a href="/edit/<%- user[item].dataValues.id %>">編輯</a> - <a href="#" data-id="<%- user[item].dataValues.id %>">刪除</a></li> <% } %> </ul>
|
調整完結果就會像這樣子
![EJS]()
接下來就是撰寫 JavaScript 啦~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const contentId = document.querySelector('#content');
contentId.addEventListener('click',(e) => { if(e.target.nodeName === 'A') { if(confirm('你確定要刪除該筆資料?')) { fetch(`/delete/${e.target.dataset.id}`,{ method: 'delete' }).then((respons) => { return respons.json() }).then((respons)=> { console.log(respons) }).catch((error) => { console.log(error); }) } } });
|
接下來就是 router 部分
1 2 3 4 5 6 7 8 9 10 11 12
| .delete('/delete/:id', async (ctx, next) => { await models.User.destroy( { where: { id: ctx.params.id } }).then(async () => { console.log('刪除成功'); ctx.body = {errmsg:'ok',errcode:0}; }) ctx.body = { errmsg:'ok',errcode:0 }; })
|
最後就可以實際來刪除看看哩~
(我已經先刪除一個 ID 1 了,這邊來測試刪除 ID 3)
![ID 3]()
![確定要刪除?]()
刪除成功後資料庫就會刪除這筆資料了
![刪除成功]()
補充
這邊有幾個地方必須注意
- 新增資料與更新資料時欄位必須相同,否則會出錯
- 在 express 是使用
req.send()
回傳 AJAX 訊息,但在 koa 是使用 ctx.body