6.实现用户名登陆:
* 1.创建服务
* 2.判断路径并处理url(url),获取主机名(os)并判断
* 3.登陆页面
* 4.获取url用户名和密码
* 5. 执行登陆
Dir.js:
const http = require('http');
const {URL} = require('url');
const os = require('os');
const fs = require('fs');
const dologin = require('./dologin.js');
http.createServer(function (req,res) {
const url = new URL(req.url,'http://'+os.constants.hostname);
if (url.pathname === '/login'){
fs.readFile('index.html',function (err,data) {
if (err) throw err;
res.end(data);
})
}else if(url.pathname ==='/dologin'){
// 实例化,并获取用户名和密码
const user = new dologin(url.searchParams.get('username'),url.searchParams.get('password'));
user.on('loginSuccess',function () {
res.writeHead(200,{'content-type':'text/html;charset=utf8'});
res.end('登陆成功');
});
user.on('loginError',function () {
res.writeHead(200,{'content-type':'text/html;charset=utf8'});
res.end('登陆失败');
});
user.login();//执行登陆
}
}).listen(8005,function () {
console.log('http servers is runing on port 8005');
});
Index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陆</title>
</head>
<body>
<form action="/dologin">
用户名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
<button>登陆</button>
</form>
</body>
</html>
Dologin.js:
const EventEmitter = require('events');
class UserBean extends EventEmitter {
constructor(username, password) {
super();
this.username = username;
this.password = password;
}
login() {
if (this.username === 'admin' && this.password === '123456') {
this.emit('loginSuccess');
console.log('成功');
} else {
this.emit('loginError');
}
}
}
module.exports = UserBean;