Node.js实现登录注册功能

本文实例为大家分享了Node.js实现登录注册功能的具体代码,供大家参考,具体内容如下
目录结构
Node.js实现登录注册功能
文章图片

注册页面:
reg.html

- 锐客网用户注册


登录页面:
【Node.js实现登录注册功能】login.html
- 锐客网用户登录


app.js
const http = require("http"); const fs = require("fs"); const url = require("url"); const querystring = require("querystring"); const post = 3000; //通过http模块创建服务器,并监听端口3000const server = http.createServer(); server.on("request",(req,res)=>{const dataurl = url.parse(req.url); //静态伺服//默认进入reg.html页面 if((req.url == "/" || req.url == "/reg.html") && req.method == "GET" && req.url != "/favicon.ico"){fs.readFile("./reg.html","utf8",(err,data)=>{if(err){fs.readFile("./404.html","utf8",(err,data)=>{res.end(data); })}res.setHeader("Content-type","text/html"); res.end(data); })//读取login.html}else if(req.url == "/login.html" && req.method == "GET"){fs.readFile("./login.html","utf8",(err,data)=>{if(err){fs.readFile("./404.html","uft8",(err,data)=>{res.end(data); })}res.setHeader("Content-type","text/html"); res.end(data); })//读取index.html}else if(req.url == "/index.html" && req.method == "GET"){fs.readFile("./index.html","utf8",(err,data)=>{if(err){fs.readFile("./404.html","uft8",(err,data)=>{res.end(data); })}res.setHeader("Content-type","text/html"); res.end(data); })//读取reg.css}else if(req.url == "/src/css/reg.css" && req.method == "GET"){fs.readFile("src/css/reg.css","utf8",(err,data)=>{if(err){console.log(err); }res.setHeader("Content-type","text/css"); res.end(data); })//读取jquery}else if(req.url == "/node_modules/jquery/dist/jquery.js" && req.method == "GET"){fs.readFile("./node_modules/jquery/dist/jquery.js","utf8",(err,data)=>{if(err){console.log(err); }res.end(data); })}})server.listen(post);

注册接口:
/register
else if(req.url == "/register" && req.method == "POST"){let str = ''; req.on('data',(chunk)=>{str += chunk; })req.on('end',()=>{let dataObj = querystring.parse(str); fs.readFile("./data.json","utf8",(err,data)=>{let obj = JSON.parse(data); for(let i = 0; i < obj.length; i++){if(obj[i].username == dataObj.username){return res.end('3'); }}obj.push(dataObj); fs.writeFile('./data.json',JSON.stringify(obj),'utf8',(err,result)=>{if(err){return res.end('2'); }return res.end('1'); })})})}

登录接口:
/login
else if(dataurl.pathname == "/login" && req.method == "GET"){console.log(dataurl); var userInput = querystring.parse(dataurl.query); fs.readFile("./data.json","utf8",(err,data)=>{let obj = JSON.parse(data); for(let i = 0; i < obj.length; i++){if(obj[i].username == userInput.username && obj[i].password == userInput.password){return res.end('1'); }else if(obj[i].username == userInput.username && obj[i].password != userInput.password){return res.end('3'); }}})}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读