查詢item_table表中的商品數據後,返回給前臺,並將回調函數做爲模塊導出。html
示例代碼:/lesson29/router/list.js前端
const connection = require('../lib/database')
module.exports = async (res, query, post, files) => {
try {
// 查詢商品列表
const data = await connection.query(`SELECT * FROM item_table`)
res.writeJson({
error: 0, // error爲0則表示接口正常
data // 查詢到的商品列表數據
})
} catch (error) {
console.error(error)
res.writeJson({
error: 1, // error爲1則表示接口出錯
msg: '數據庫出錯' // 接口的錯誤信息
})
}
res.end()
}
複製代碼
應禁止query語句使用以下寫法,容易形成注入攻擊。 connection.query(INSERT INTO item_table (title, price, count) VALUES('${title}, ${price} ${count}')
) 此時若用戶傳入參數以下:jquery
http://localhost:8080/add?title=a')%3B%20DELETE%20FROM%20item_table%3B%20SELECT%20(1&price=19.8&count=200git
就會讓服務器執行一個這樣的語句:github
INSERT INTO item_table (title, price, count) VALUES('a'); DELETE FROM item_table; SELECT ('1', 19.8, 200)
複製代碼
其意義爲:ajax
這樣就會致使item_table表中的全部數據被刪除。數據庫
爲防止注入攻擊,能夠使用佔位符?代替須要插入數據庫的參數,第二個數組參數中的3個值會按順序填充佔位符,該方法能夠避免大部分注入攻擊,以下:json
await connection.query(`INSERT INTO item_table (title, price, count) VALUES(?,?,?)`, [title, price, count])
複製代碼
示例代碼:/lesson29/router/add.js數組
const connection = require('../lib/database')
module.exports = async (res, query, post, files) => {
let {
title,
price,
count
} = post
// 判斷是否有傳參
if (!title || !price || !count) {
res.writeJson({
error: 1,
msg: '參數不合法'
})
} else {
// 將價格和數量轉爲數字
price = Number(price)
count = Number(count)
// 判斷價格和數量是否非數字
if (isNaN(price) || isNaN(count)) {
res.writeJson({
error: 1,
msg: '參數不合法'
})
} else {
try {
// 使用佔位符?代替須要插入數據庫的參數,第二個數組參數中的3個值會按順序填充佔位符,該方法能夠避免大部分注入攻擊。
await connection.query(`INSERT INTO item_table (title, price, count) VALUES(?,?,?)`, [title, price, count])
res.writeJson({
error: 0,
msg: '添加商品成功'
})
} catch (error) {
console.error(error)
res.writeJson({
error: 1,
msg: '數據庫內部錯誤'
})
}
}
}
res.end()
}
複製代碼
示例代碼:/lesson29/router/del.jsbash
const connection = require('../lib/database')
module.exports = async (res, query, post, files) => {
const ID = query.id
if (!ID) {
res.writeJson({
error: 1,
msg: '參數不合法'
})
} else {
await connection.query(`DELETE FROM item_table WHERE ID=${ID}`)
res.writeJson({
error: 0,
msg: '刪除成功'
})
}
res.end()
}
複製代碼
在/router/index.js
中,引用各個接口的配置,並用addRouter方法添加到路由表中,便可在接收到請求時,查找路由並進行處理。
示例代碼:/lesson29/router/index.js
const {
addRouter
} = require('../lib/router')
// 添加獲取商品列表接口
addRouter('get', '/list', require('./list'))
// 添加商品接口
addRouter('post', '/add', require('./add'))
// 刪除商品接口
addRouter('get', '/del', require('./del'))
複製代碼
在/server.js中,引用router模塊,就能夠完成整個服務端的配置。
示例代碼:/lesson29/server.js
const connection = require('./lib/database')
const http = require('./lib/http')
const router = require('./router')
複製代碼
在/static/index.html
中,使用jquery爲前端頁面實現以下功能:
示例代碼:/lesson29/server.js
// 查詢商品列表的方法
function getList() {
$.ajax({
url: '/list',
dataType: 'json'
}).then(res => {
let html = ``
res.data.forEach((item, index) => {
html += (
`
<tr>
<td>${item.title}</td>
<td>¥${item.price}</td>
<td>${item.count}</td>
<td>
<a data-id="${item.ID}" href="#" class="glyphicon glyphicon-trash">刪除</a>
</td>
</tr>
`
)
})
$('tbody').html(html)
});
} getList()
// 點擊添加按鈕,隨機添加一個商品
$('#addBtn').on('click', function () {
$.ajax({
url: '/add',
method: 'post',
data: {
title: `test${Math.floor(Math.random() * 100)}`,
price: Math.floor(Math.random() * 100),
count: Math.floor(Math.random() * 100)
}
})
.then((response) => {
getList()
})
})
// 點擊刪除按鈕
$('tbody').on('click', 'a', function () {
$.ajax({
url: '/del',
data: {
id: $(this).attr('data-id')
}
})
.then((response) => {
getList()
})
})
複製代碼
至此,原生Node.js的項目就所有完成了,這個項目「麻雀雖小五臟俱全」,能夠很好地鍛鍊咱們對Node.js的理解和開發能力。 固然從開發的過程也能夠看到,使用原生Node.js開發效率較低,實際工做中仍是會更多地使用Express、Koa等框架,進一步提升開發效率。