新手请教代码逻辑问题
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
我觉得这个没有什么可纠结吧,每个人可以自己的逻辑,老师讲的是他自己的逻辑,最终结果一样应该就行,比如我自己写的就跟老师的不同。重在理解吧
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);举报