app設(shè)計(jì)網(wǎng)站模板/google優(yōu)化師
// 創(chuàng)建服務(wù)
const app = http.createServer((req, res)=>{
? ? // 設(shè)置給前端返回信息的字符編碼
? ? res.setHeader('content-type', 'text/html; charset=utf-8')?? ?
? ? let address = req.url.split('?')[0]
? ? //首先創(chuàng)建一個(gè)數(shù)組,后面把它的數(shù)據(jù)放在JSON文件
? ? let user = [{id: 1, username: 'user1', password: '123'}]
? ? //拿到query,它是一個(gè)對象,里面有ID,usermane,password
? ? let objParams = url.parse(req.url, true).query
console.log(url.parse(req.url, true))
? ? // 使用switch進(jìn)行匹配
? ? switch(address){
? ? ? ? // 頁面的靜態(tài)托管
? ? ? ? case '/index.html':
? ? ? ? ? ? fs.readFile('./index.html', 'utf-8', (err, data)=>{
? ? ? ? ? ? ? ? res.end(data)
? ? ? ? ? ? })
? ? ? ? ? ? break
? ? ? ? case '/login.html':
? ? ? ? ? ? fs.readFile('./login.html', 'utf-8', (err, data)=>{
? ? ? ? ? ? ? ? res.end(data)
? ? ? ? ? ? ?}) ??
? ? ? ? ? ? ?break
? ? ? ?
? ? ? ? case '/user/login':
? ? ? ? ? ? // res.end(JSON.stringify({code: 1, message: '登錄成功'}))
? ? ? ? ? ? // 把傳遞過來的參數(shù)和db數(shù)據(jù)庫里面的參數(shù)進(jìn)行對比
? ? ? ? ? ? fs.readFile('./db/register.json', 'utf-8', (err, data)=>{
? ? ? ? ? ? ? ? let {username, password} = objParams
? ? ? ? ? ? ? ?// ?console.log(username, password)
? ? ? ? ? ? ? ? let result = JSON.parse(data).find(item=>{
? ? ? ? ? ? ? ? ? ? return item.username === username && item.password === password?
? ? ? ? ? ? ? ? })
? ? ? ? ? ? ? ? if(!result){
? ? ? ? ? ? ? ? ? ? // 注意點(diǎn):如果驗(yàn)證不通過,必須返回的是用戶名或者密碼錯(cuò)誤,這樣可以增加安全性
? ? ? ? ? ? ? ? ? ? res.end(JSON.stringify({code: 0, message: '用戶名或者密碼錯(cuò)誤'}))
? ? ? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? ? ? res.end(JSON.stringify({code: 1, message: '登錄成功'}))
?? ??? ??? ??? ??? ?
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }) ??
? ? ? ? ? ? break
? ? ? ? case '/shopping/list':
? ? ? ? ? ? fs.readFile('./db/goods.json', 'utf-8', (err, data)=>{
? ? ? ? ? ? ? ? res.end(data)
? ? ? ? ? ? }) ??
? ? ? ? case '/user/register':
? ? ? ? ? ? // fs.writeFile('./db/register.json', JSON.stringify(user), ()=>{
? ? ? ? ? ? // ? ? res.end(JSON.stringify({code: 1, message: '注冊成功'}))
? ? ? ? ? ? // })
? ? ? ? ? ? // 先讀,再寫
? ? ? ? ? ? fs.readFile('./db/register.json', 'utf-8', (err,data)=>{
? ? ? ? ? ? ? ? user.push(objParams)
?? ??? ?console.log(data)
? ? ? ? ? ? ? ? fs.writeFile('./db/register.json', JSON.stringify(user), ()=>{
?? ??? ??? ?
? ? ? ? ? ? ? ? ? ? res.end(JSON.stringify({code: 1, message: '注冊成功'}))
?? ??? ??? ??? ??? ?
? ? ? ? ? ? ? ? })
? ? ? ? ? ? })
? ? ? ? ? ? break
? ? ? ? default:
? ? ? ? ? ? res.end('<h1>404,你的頁面走丟了!</h1>')?
? ? }
})
// 監(jiān)聽端口號
app.listen(2307, ()=>{
? ? console.log('你的服務(wù)器已經(jīng)開啟了,快來玩啊!http://localhost:2307')
})