新手請教代碼邏輯問題
??????fs.readFile(`${path}`,?(err,?data)?=>?{
????????if?(err)?{
??????????res.end("404")
????????}?else?{
??????????res.end(data)
????????}
??????})
讀取login文件怎么為什么要寫在complete回調函數里面啊?前面不是要判斷請求方式method是GET還是POST才會調用complete函數的嗎?
??????fs.readFile(`${path}`,?(err,?data)?=>?{
????????if?(err)?{
??????????res.end("404")
????????}?else?{
??????????res.end(data)
????????}
??????})
讀取login文件怎么為什么要寫在complete回調函數里面啊?前面不是要判斷請求方式method是GET還是POST才會調用complete函數的嗎?
2020-11-19
舉報
2020-11-22
我覺得這個沒有什么可糾結吧,每個人可以自己的邏輯,老師講的是他自己的邏輯,最終結果一樣應該就行,比如我自己寫的就跟老師的不同。重在理解吧
const?http?=?require('http'); const?fs?=?require('fs'); const?querystring?=?require('querystring'); const?registeredUserInfos?=?{}; http.createServer((req,?resp)?=>?{ ????if?(req.method?==?'GET')?{ ????????fs.readFile(`./${req.url}`,?(err,?data)?=>?{ ????????????if?(err)?{ ????????????????resp.writeHead(404); ????????????????resp.end('Page?not?found.'); ????????????}?else?{ ????????????????resp.end(data); ????????????} ????????}); ????}?else?if?(req.method?==?'POST')?{ ????????let?data?=?[]; ???????? ????????req.on('data',?(chunk)?=>?{ ????????????data?+=?chunk; ????????}); ???????? ????????req.on('end',?()?=>?{ ????????????let?params?=?querystring.parse(data); ????????????if?(params.action?==?'reg')?{ ????????????????if?(registeredUserInfos[params.username])?{ ????????????????????resp.writeHead(500); ????????????????????resp.end('Invalid?user?account,?Please?choose?other?to?try.'); ????????????????else?{ ????????????????????registeredUserInfos[params.username]?=?params; ????????????????????resp.end('Registered?successfully!'); ????????????????} ????????????}?else?if?(params.action?==?'login')?{ ????????????????if?(!registeredUserInfos[params.username])?{ ????????????????????resp.writeHead(500); ????????????????????resp.end('Invalid?user?account,?Please?choose?other?to?try.'); ????????????????}?else?{ ????????????????????let?userinfo?=?registeredUserInfos[params.username]; ????????????????????if?(params.password?==?userinfo.password)?{ ????????????????????????resp.end('Login?successfully'); ????????????????????}?else?{ ????????????????????????resp.end('Invalid?user?password,?Please?choose?other?to?try.'); ????????????????????} ????????????????} ????????????}?else?{ ????????????????resp.writeHead(500); ????????????????resp.end('Invalid?action,?Please?choose?other?to?try.'); ????????????} ????????}); ????} }).listen(3000);