• 登录注册页面的模拟


    流程:

    前端:
    1.注册
    2.登录
    3.首页

    后端:
    1.注册
    url:/register
    type:post
    params:{
        user:'******'(require),
        pwd:'******'(require)
    }
    res:{
        code:200,
        status:1,(0 注册失败,1 注册成功),
        err:'失败原因',
        info:{
            userID:1,(后台生成)
            user:'******',
            pwd:'******'
        },
        msg:"注册成功"
    }

    2.登录
    req:
    url:/login
    type:post
    params:{
        user:'******'(require),
        pwd:'******'(require)
    }

    接下来,按照上述流程写后端:

    1.创建user.json

     

    2.创建app.js

    1. const http = require('http');
    2. const { URL } = require('url');
    3. const fs = require('fs');
    4. const path = require('path');
    5. // 引⼊模块
    6. const mime = require('./mime.json')
    7. // req:请求,后端给前端
    8. // res:响应,前端给后端
    9. http.createServer((req, res) => {
    10. // 将req.url 进⾏处理
    11. let myUrl = new URL('http://localhost:3000' + req.url);
    12. let url = myUrl.pathname; //路由
    13. static(req, res, myUrl); //是否读取静态⽂件
    14. if (url === '/register') {
    15. //注册
    16. doPost(req, (obj) => {
    17. doRegister(res, obj);
    18. });
    19. } else if (url === '/login') {
    20. //登录
    21. doPost(req, (obj) => {
    22. doLogin(res, obj);
    23. });
    24. }
    25. }).listen(3000, () => {
    26. console.log('http server is running on port 3000')
    27. })
    28. // 读取静态⽂件
    29. function static(req, res, myUrl) {
    30. if (myUrl.pathname.includes('.')) {
    31. // 说明这是个静态⽂件
    32. // 1. 确定静态⽂件的路径
    33. let filepath = __dirname + myUrl.pathname;
    34. // ⽂件后缀名
    35. let ext = path.extname(filepath);
    36. let type = mime[ext];
    37. // 2. 读取他
    38. fs.readFile(filepath, (err, data) => {
    39. // 3. 返回他
    40. // ⼀定要写响应头
    41. res.writeHead(200, { 'content-type': type })
    42. res.end(data);
    43. })
    44. }
    45. }
    46. // 完成post数据接收
    47. function doPost(req, cb) {
    48. let data = ''; //数据
    49. // 分段接收数据
    50. req.on('data', chunk => {
    51. // chunk是个buffer(二进制数据流)
    52. data += chunk;
    53. })
    54. // 数据接受完毕
    55. req.on('end', () => {
    56. let obj = search2obj(data.toString());
    57. cb(obj); //调⽤回调函数
    58. })
    59. }
    60. function search2obj(string) {
    61. // string = 'key=value&key=value'
    62. let obj = {};
    63. // 先分离 &
    64. let arr = string.split('&');
    65. arr.forEach(str => {
    66. // str = 'key=value'
    67. // 再分离 =
    68. let arr2 = str.split('=');
    69. // arr2 = ['key', 'value']
    70. let key = arr2[0];
    71. let value = arr2[1];
    72. obj[key] = value;
    73. })
    74. return obj;
    75. }
    76. function doLogin(res, obj) {
    77. // let obj = {
    78. // user: myUrl.searchParams.get('user'),
    79. // pwd: myUrl.searchParams.get('pwd')
    80. // }
    81. if (!myRule(obj.user) || !myRule(obj.pwd)) {
    82. // 不合规
    83. res.end(JSON.stringify({
    84. code: 200,
    85. status: 0,
    86. err: '⽤户名或者密码请按规定填写!'
    87. }))
    88. return;
    89. }
    90. let users = getAllUsers();
    91. if (!users) {
    92. // 读取内容失败
    93. res.end(JSON.stringify({
    94. code: 200,
    95. status: 0,
    96. err: '系统繁忙,请稍后再试!'
    97. }))
    98. return;
    99. }
    100. users = JSON.parse(users);
    101. let uu = null; //⽬标⽤户
    102. // 判断⽤户名是否⼀样
    103. users.some(item => {
    104. if (item.user === obj.user) {
    105. uu = item;
    106. return true;
    107. }
    108. return false;
    109. })
    110. if (!uu || uu.pwd !== obj.pwd) {
    111. // ⽤户不存在或密码错误
    112. res.end(JSON.stringify({
    113. code: 200,
    114. status: 0,
    115. err: 'user or pwd is wrong!'
    116. }))
    117. return;
    118. }
    119. res.writeHead(200, { 'content-type': 'text/html;charset=utf-8' })
    120. res.end(`
    121. <script>
    122. alert('登录成功');
    123. location.href = 'http://localhost:3000/ll/index.html';
    124. </script>
    125. `)
    126. }
    127. function doRegister(res, obj) {
    128. // console.log(req);
    129. //处理 searchParams to obj
    130. // get 提交数据在req.url⾥
    131. // post 提交 需要使⽤事件来接受
    132. // let obj = {
    133. // user: myUrl.searchParams.get('user'),
    134. // pwd: myUrl.searchParams.get('pwd')
    135. // }
    136. console.log(obj);
    137. // 判断 ⽤户名 密码是否合规
    138. if (!myRule(obj.user) || !myRule(obj.pwd)) {
    139. // 不合规
    140. res.end(JSON.stringify({
    141. code: 200,
    142. status: 0,
    143. err: '⽤户名或者密码请按规定填写!'
    144. }))
    145. return;
    146. }
    147. // 2. 获取 user.json 所有的数据
    148. let users = getAllUsers();
    149. if (!users) {
    150. // 读取内容失败
    151. res.end(JSON.stringify({
    152. code: 200,
    153. status: 0,
    154. err: '系统繁忙,请稍后再试!'
    155. }))
    156. return;
    157. }
    158. // 3. 判断 obj.user是否存在
    159. users = JSON.parse(users);
    160. if (users.some(item => item.user === obj.user)) {
    161. // 存在
    162. res.end(JSON.stringify({
    163. code: 200,
    164. status: 0,
    165. err: '⽤户名已存在!'
    166. }))
    167. return;
    168. }
    169. // 为obj添加⼀个id
    170. obj.id = users.length + 1;
    171. users.push(obj);
    172. // 将users重新写⼊ user.json
    173. reSetUsers(users);
    174. res.writeHead(200, { 'content-type': 'text/html;charset=utf-8' })
    175. res.end(`
    176. <script>
    177. alert('注册成功');
    178. location.href = 'http://localhost:3000/ll/login.html';
    179. </script>
    180. `)
    181. }
    182. // 正则 验证
    183. // 规则:不允许出现特殊符号, 6-20位
    184. function myRule(string) {
    185. const rule = /^\w{6,20}$/;
    186. return rule.test(string);
    187. }
    188. // 获取 user.json 的数据
    189. function getAllUsers() {
    190. let path = __dirname + '/db/user.json';
    191. return fs.readFileSync(path, 'utf8');
    192. }
    193. // 重新写⼊ user.json
    194. function reSetUsers(users) {
    195. let path = __dirname + '/db/user.json';
    196. return fs.writeFileSync(path, JSON.stringify(users));
    197. }

    3.编写前端页面

    创建index.html,login.html,register.html

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>首页</title>
    8. </head>
    9. <body>
    10. <h1>欢迎来到聊聊</h1>
    11. </body>
    12. </html>
    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>登录</title>
    8. <link rel="stylesheet" href="css/public.css">
    9. </head>
    10. <body>
    11. <h1>登录</h1>
    12. <form action="/login" method="post">
    13. <div class="user">
    14. <input type="text" name="user" placeholder="请输入用户名" required>
    15. </div>
    16. <div class="pwd">
    17. <input type="password" name="pwd" placeholder="请输入密码" required>
    18. </div>
    19. <input type="submit">
    20. </form>
    21. </body>
    22. </html>

     

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>注册</title>
    8. <link rel="stylesheet" href="css/public.css">
    9. </head>
    10. <body>
    11. <h1>注册</h1>
    12. <form action="/register" method="post">
    13. <div class="user">
    14. <input type="text" name="user" placeholder="请输入用户名" required>
    15. </div>
    16. <div class="pwd">
    17. <input type="password" name="pwd" placeholder="请输入密码" required>
    18. </div>
    19. <input type="submit">
    20. </form>
    21. </body>
    22. </html>

    终端开启:

     

    服务器:

     

     

    点击确定跳转到登录页面

     

     

    点击确定跳转到首页

     

     看user.json中此时已经有了刚才的数据

     

  • 相关阅读:
    大模型,教培机构要过窄门
    探索Java中的正则表达式:从基础到高级应用
    别试错了,是该关注一下软件内在质量了
    葡萄糖-聚乙二醇-四嗪/叶酸/多巴胺 Glucose-PEG-TZ/FA/Dopamine
    【OpenPLC】在linux板卡上添加CANOpen功能
    失业在家的6个月,我通过外包全款买了房:你看不起的行业,往往很赚钱
    【pen200-lab】10.11.1.39
    MapRdeuce工作原理
    十分钟学会Golang开发gRPC服务
    颜色分类(中等)
  • 原文地址:https://blog.csdn.net/weixin_52993364/article/details/125431726