• 结合GET(),POST()实现一个简单、完整的服务器


    复习一下:

    基础模块 作用
    fs fs模块用于对系统文件及目录进行读写操作
    http 创建服务器。e.g.http.createServer();
    queryString 把url带的参数串转化为数组对象
    url 直接解析URL中字符串,提炼出我们需要的结果。
    提示:
        querystring主要用来解析POST数据(如‘querystring.parse()’)
        Url主要用来解析GET数据(比如‘url.parse()’)。
    
    1.url.parse()方法回顾:
     var url = require('url');
     var queryUrl = "http://localhost:8888/bb?name=bigbear&memo=helloworld" 
     console.log(url.parse(queryUrl)) ;
    

    运行结果:

    { 
        protocol: 'http:',
        slashes: true,
        auth: null,
        host: 'localhost:8888',
        port: '8888',
        hostname: 'localhost',
        hash: null,
        search: '?name=bigbear&memo=helloworld',
        query: 'name=bigbear&memo=helloworld',
        pathname: '/bb',
        path: '/bb?name=bigbear&memo=helloworld',
        href: 'http://localhost:8888/bb?name=bigbear&memo=helloworld'
    }
    

    说明:

    query: 查询字符串中的参数部分(问号后面部分字符串),或者使用 querystring.parse() 解析后返回的对象。

    2.querystring.parse()方法回顾

    QueryString" 模块用于实现URL参数字符串与参数对象的互相转换
    在url.parse()基础上,把参数字符串编程jsonp对象格式:

    例子:

    思路:

    一、首先,我们确定一下接口。
    /user?act=reg&user=aaa&pass=123456
    	{"ok": false, "msg": "原因"}
    
    /user?act=login&user=aaa&pass=123456
    	{"ok": true, "msg": "原因"}
    
    二、 文件位置:

    三、服务器接受数据后,处理并返回data的思路
    1. 接口名为user。如果url中地址不指向user,就显示404,否则进入2;
    2. 用户是登录还是注册?
    3. 如果既不是注册也不是登录。就提示“未知action”;
      4.“登录部分”接下去是如果密码正确,就提示“登录成功”,否则提示“密码不正确”;
      如果是注册,检测账号是否存在,也进行相应的提示。
    const http = require('http');
    const fs = require('fs');
    const querystring = require('querystring');
    const urlLib = require('url');
    
    var users = {}; //将注册信息保存在缓存中
    
    var server = http.createServer(function (req, res) {
        // 解析数据    
        var str = '';
        req.on("data", function (data) {
            str += data;
        });
        req.on("end", function () {
            var obj = urlLib.parse(req.url, true);
    
            var url = obj.pathname;
            const GET = obj.query;
            const POST = querystring.parse(url);
    
            // 区分接口和文件读取
            if (url == '/user') { //读取‘url’接口下的文件时
                switch (GET.act) {
                    case 'reg':
                        //用户名已经存在 
                        if (users[GET.user]) {
                            res.write('{"ok":false, "msg":"已经注册过了!"}');
                        } else {
                            // 插入到users
                            users[GET.user] = GET.pass;
                            res.write('{"ok":true,"msg":"注册成功!"}');
                        }
                        break;
                    case 'login':
                        //用户名是否存在
                        if (users[GET.user]) {
                            if (user[GET.pass] === GET.pass) { //密码是否正确
                                res.write('{"ok":true,"msg":"登录成功!"}');
                            } else {
                                res.write('{"ok":flase,"msg":"密码不正确!"}');
                            }
                        } else { //用户名不存在
                            res.write('{"ok":false,"msg":"用户名不存在"}');
                        }
                        break;
                    default:
                        res.write('{"ok":false,"msg":"未知操作"}');
                }
                res.end();
            } else { //读取别的文件
                var file_name = './www' + url;
                fs.readFile(file_name, function (err, data) {
                    if (data) {
                        res.write(data);
                    } else {
                        res.write("404");
                    }
                    res.end();
                });
            }
        });
    });
    
    server.listen(8080);
    

    user.html文件代码:

    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
      <title></title>
      <!--引入jQuery文件-->
      <script src="ajax.js" charset="utf-8"></script>
      
      <!--我们需要的js代码-->
      <script type="text/javascript">
        window.onload = function () {
          var oTxtUser = document.getElementById('user');
          var oTxtPass = document.getElementById('pass');
          var oBtnReg = document.getElementById('reg_btn');
          var oBtnLogin = document.getElementById('login_btn');
    
          oBtnLogin.onclick = function () {
            ajax({
              url: '/user',
              data: {
                act: 'login',
                user: oTxtUser.value,
                pass: oTxtPass.value
              },
              type: 'get',
              success: function (str) {
                var json = eval('(' + str + ')');
    
                if (json.ok) {
                  alert('登录成功');
                } else {
                  alert('登录失败:' + json.msg);
                }
              },
              error: function () {
                alert('通信错误');
              }
            });
          };
    
          oBtnReg.onclick = function () {
            ajax({
              url: '/user',
              data: {
                act: 'reg',
                user: oTxtUser.value,
                pass: oTxtPass.value
              },
              type: 'get',
              success: function (str) {
                var json = eval('(' + str + ')');
    
                if (json.ok) {
                  alert('注册成功');
                } else {
                  alert('注册失败:' + json.msg);
                }
              },
              error: function () {
                alert('通信错误');
              }
            });
          };
        };
      </script>
    </head>
    
    <body>
      用户:
      <input type="text" id="user">
      <br> 密码:
      <input type="password" id="pass">
      <br>
      <input type="button" value="注册" id="reg_btn">
      <input type="button" value="登录" id="login_btn">
    </body>
    
    </html>
    

    执行以下server.js,然后在浏览器中打开user.html页面。值得注意的是跨域问题,

    注意:我们应该在服务器上跑,而不是只打开本地静态页面!

    接下来就正常玩耍吧……

  • 相关阅读:
    POJ 1509 Glass Beads【字符串最小表示法】
    Codeforces 665C Simple Strings【暴力,贪心】
    Codeforces 665D Simple Subset【构造】
    HDU 5667 Sequence【矩阵快速幂+费马小定理】
    Codeforces 667D World Tour【最短路+枚举】
    Codeforces 667D World Tour【最短路+枚举】
    HDU 5676 ztr loves lucky numbers【DFS】
    Codeforces 667C Reberland Linguistics【DFS】
    前端学习笔记三
    Datawhale编程——动态规划DP
  • 原文地址:https://www.cnblogs.com/n2meetu/p/7837600.html
Copyright © 2020-2023  润新知