Node.js-Node事件机制实例讲解

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;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值