How to write mysql in nodejs:
//连接池 let db=mysql.createPool({'配置'}) db.query(`sql语句`,(err,data)=>{})
And the password stored in the database should be ciphertext
function md5(str){ let obj=crypto.createHash('md5'); obj.update(str); return obj.digest('hex') } function md5_2(str){ return md5(md5(str)) }
Server-side operation, a simple verification is added to the user name and password , not perfect, needs improvement
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);
The above is the detailed content of How to implement registration and login function in NodeJs+MySQL. For more information, please follow other related articles on the PHP Chinese website!