const http=require('http');const mysql=require('mysql');const url=require('url');const fs=require('fs');//1.连接到服务器
let db=mysql.createConnection({
host:'localhost',
port:3306,
user:'root',
password:'',
database:'node_sql'})if(db){console.log('sql success');}//2.配合http
http.createServer( (req,res)=>{const {pathname,query}=url.parse(req.url,true);
let{username,password}=query;if(pathname=='/reg'){ //用户想注册
if(!username || !password){
res.write('用户名和密码不能为空');
res.end();
}else if(username.length>32){
res.write('用户名最大32个字');
res.end();
}else{
db.query(`SELECT ID FROM user WHERE username='${username}'`,(err,data)=>{if(err){
res.write('数据库有错');
res.end();
}else if(data.length>0){
res.write('用户名已被注册');
res.end();
}else{
db.query(`INSERT INTO user (username,password,nickname) VALUES ('${username}','${password}','placeholder')`,(err,data)=>{if(err){
res.write('数据库有错');
res.end();
}else{
res.write('注册成功');
res.end();
}
})
}
})
}
}else if(pathname=='/login'){ //用户登录
if(!username || !password){
res.write('用户名和密码不能为空');
res.end();
}else{
db.query(`SELECT ID FROM user WHERE username='${username}'`,(err,data)=>{if(err){
res.write('数据库有错');
res.end();
}else if(data.length<=0){
res.write('用户名不存在');
res.end();
}else{
db.query(`SELECT password FROM userwhere username='${username}'`,(err,data)=>{if(err){
res.write('数据库有错');
res.end();
}else{if(data[0].password!=password){
res.write('密码错误');
res.end();
}else{
res.write('登录成功');
res.end();
}
}
})
}
})
}
}else{
fs.readFile(`www${pathname}`,(err,buffer)=>{
console.log(err,buffer);if(err){
res.writeHeader(404);
res.write('NOT FOUND');
}else{
res.write(buffer);
}
res.end();
})
}
}).listen(8520,()=>{
console.log("node_sql action");
});