nodejs中mysql的写法:
//连接池 let db=mysql.createPool({'配置'}) db.query(`sql语句`,(err,data)=>{})
并且在数据库中存储的密码应该是密文
function md5(str){ let obj=crypto.createHash('md5'); obj.update(str); return obj.digest('hex') } function md5_2(str){ return md5(md5(str)) }
服务端操作,在用户名与密码上添加了简单的校验,不完善,还需要改进
const http=require('http'); const fs=require('fs'); const mysql=require('mysql'); const url=require('url'); const zlib=require('zlib'); const crypto=require('crypto'); const _key='bsjhjqbj1;dqwxsxx+'; let server=http.createServer((req,res)=>{ let {pathname,query}=url.parse(req.url,true); let {user,password}=query; switch(pathname){ case '/reg': if(!user){ res.write('{"err":1,"msg":"用户名不能为空"}'); res.end(); }else if(!password){ res.write('{"err":1,"msg":"密码不能为空"}'); res.end(); }else if(!/\w{4,16}$/.test(user)){ res.write('{"err":1,"msg":"用户名应为大小写字母数字或下划线"}'); res.end(); }else if(/['|"]/.test(password)){ res.write('{"err":1,"msg":"密码非法"}'); res.end(); }else{ db.query(`SELECT username FROM users_table WHERE username='${user}'`,(err,data)=>{ if(err){ res.write('{"err":1,"msg":"数据库错误"}'); console.log(err) res.end() }else{ if(data.length>0){ res.write('{"err":1,"msg":"用户名已存在"}'); res.end(); }else{ res.write('{"err":0,"msg":"注册成功"}'); db.query(`INSERT INTO users_table (ID,username,password) VALUES (0,'${user}','${md5_2(password)}')`); res.end(); } } }) } break; case '/login': if(!user){ res.write('{"err":1,"msg":"用户名不能为空"}'); res.end(); }else if(!password){ res.write('{"err":1,"msg":"密码不能为空"}'); res.end(); }else if(!/\w{4,16}$/.test(user)){ res.write('{"err":1,"msg":"用户名应为大小写字母数字或下划线"}'); res.end() }else if(/["|']/.test(password)){ res.write('{"err":1,"msg":"密码非法"}'); res.end(); }else{ db.query(`SELECT username,password FROM users_table WHERE username='${user}'`,(err,data)=>{ if(err){ res.write('{"err":1,"msg":"数据库错误"}'); res.end() }else if(data.length>0){ if(md5_2(password)!=data[0].password){ res.write('{"err":1,"msg":"用户名或密码不正确"}'); res.end(); }else{ res.write('{"err":0,"msg":"登陆成功"}'); res.end(); } }else{ res.write('{"err":1,"msg":"用户不存在"}') } }) } break; default: let rs=fs.createReadStream(`www${pathname}`); let gz=zlib.createGzip(); res.setHeader('content-encoding','gzip'); rs.pipe(gz).pipe(res); rs.on('error',err=>{ res.writeHeader(404); res.write('Not Found'); res.end(); }); } }); server.listen(8888);
以上是NodeJs+MySQL怎么实现注册登录功能的详细内容。更多信息请关注PHP中文网其他相关文章!