zoukankan      html  css  js  c++  java
  • node.js 实现接口-操作文件进行用户增删改查

    首先安装npm,使用npm安装express

    npm install express -S
    
    
    /*
     * @Author: yinxin
     * @Date: 2020-03-27 10:18:41
     * @LastEditTime: 2020-03-30 20:17:26
     * @LastEditors: Please set LastEditors
     * @Description: In User Settings Edit
     * @FilePath: /vue-sdu/login.js
     */
    var express = require('express');
    var app = express();
    var fs = require("fs");
    var bodyParser = require("body-parser")
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded());
    var allowCrossDomain = function (req, res, next) {
      res.header('Access-Control-Allow-Origin', '*');//自定义中间件,设置跨域需要的响应头。
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');  //允许任何方法
      res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,X-Session-Token');   //允许任何类型
      next();
    };
    app.use(allowCrossDomain);
    var jsonParser = bodyParser.json();
    // get请求实现读取文件并返回数据
    app.get('/api/users/:username/:password', function (req, res) {
      fs.readFile(__dirname + "/users.json", 'utf8', function (err, data) {   // 读取文件 
          console.log( req.params.username );
          // console.log(JSON.parse(data),typeof JSON.parse(data))
          var status = {"msg":"用户名密码错误","status":false,data:""}  //定义一个返回的固定格式  
          if(req.params.username){
            var jsonData = JSON.parse(data);
            console.log(req.params);
            for(var i = 0; i < jsonData.length;i++){
              if(req.params.username == jsonData[i].name && req.params.password == jsonData[i].password){
                if (req.params.username == "admin"){   // 当请求用户为admin时,验证成功则返回所有数据
                  console.log("admin")
                  status.data  = JSON.stringify(jsonData);
                  status.status = true;
                  status.msg = "验证成功。";
                }else{
                  status.status = true;
                  status.msg = "验证成功。";
                  status.data = JSON.stringify(jsonData[i]);  // 普通用户返回当前登录用户数据
                }
              }
            }
            console.log(status);
            res.end( JSON.stringify(status));  
        };
        })   
    });
    ///添加用户 
    app.post('/api/users/add', jsonParser, function(req,res){
      fs.readFile(__dirname + "/users.json",function(err,data){
        if(err){
            req.end(err)
        }
        console.log(req.params)
        console.log(req.body)
        // console.log(req)
    
        params={
          "name":req.query.name,
          "password":req.query.password,
          "age":req.query.age
        }
        console.log(req.query)
        var person = data.toString();//将二进制的数据转换为字符串
        person = JSON.parse(person);//将字符串转换为json对象
        console.log(person)
        person.push(params);//将传来的对象push进数组对象中
        console.log(person.data);
        var str = JSON.stringify(person);//因为nodejs的写入文件只认识字符串或者二进制数,所以把json对象转换成字符串重新写入json文件中
        fs.writeFile(__dirname + "/users.json",str,function(err){
            if(err){
              res.end(err)
            }
            res.end(JSON.stringify(str))
        });
    });
    });
    
    var server = app.listen(8081, function () {
      var host = server.address().address
      var port = server.address().port
      console.log("访问地址为 http://%s:%s", host, port)
    });
    
    
    
    user.json 

    [{"name":"user","password":"456","age":"23"},{"name":"user2","password":"456","age":"44"},{"name":"user3","password":"456","age":"34"},{"name":"admin","password":"admin","age":"12"},{"name":"yinxin","password":"123","age":"12"},{"name":"yinxin1","password":"123","age":"12"},{"name":"yinxin1","password":"123","age":"12"}]
    
    
    
     login.html

    <!--
     * @Author: your name
     * @Date: 2020-03-27 12:20:04
     * @LastEditTime: 2020-03-28 21:59:13
     * @LastEditors: Please set LastEditors
     * @Description: In User Settings Edit
     * @FilePath: /vue-sdu/login1.html
     -->
     <!doctype html>
     <html>
     <head>
     <meta charset="utf-8">
     <link rel="stylesheet" href="./login.css">
     <title>login</title>
     <style type="text/css">
     
     </style>
     </head>
      
     <body>
     <div class="header" id="head">
       <div class="title">金渡教育</div>
       
     </div>
       
     <div class="wrap" id="wrap">
       <div class="logGet">
           <!-- 头部提示信息 -->
           <div class="logD logDtip">
             <p class="p1">登录</p>
           </div>
           <!-- 输入框 -->
           <form method="get" onsubmit="return false">
            <div class="lgD">
              <input type="text" id="username" required="required"
                placeholder="输入用户名" />
            </div>
            <div class="lgD">
              <input type="password" id="password" required="required"
                placeholder="输入用户密码" />
            </div>
            <div class="logC">
              <a target="_self"><button type="submit" onclick="sendData()">登录</button>
              </a>
              <span id="message"></span>
            </div>
          </form>
           
         </div>
     </div>
       
     <div class="footer" id="foot">
       <div class="copyright">
         <p>Copyright © 2020 Qunar.com Inc. All Rights Reserved.</p>
         <div class="img">
         <i class="icon"></i><span>联系邮箱:yinxin918@163.com</span>
       </div>
     
      
       </div>
       
     </div>
    
     <script>
      function sendData(){
          var name = document.getElementById("username").value;
          var password = document.getElementById("password").value;
          var xmlhttp = new XMLHttpRequest();
          if (name && password){
             //open---指定一个接口(url, method)
            xmlhttp.open("get", "http://localhost:8081/api/users/"+name+"/"+password); //异步
            xmlhttp.send(); //发送
            xmlhttp.onreadystatechange = function() { //接收数据
              //4--node服务响应完成   200---成功
              if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                  //把拿到的数据展示出来 写入dom
                  // content.innerHTML = xmlhttp.responseText; //conten 简写
                  data = JSON.parse(xmlhttp.responseText)
                  console.log(data)
                  if (data.status){
                    document.getElementById("message").innerHTML = data.msg
                      
                    location.href = "index.html?data="+JSON.stringify(data)
                  }else{
                    document.getElementById("message").innerHTML = data.msg
                  }
              }
          }
    
    
          }
         
    
      }
    </script>
       
       
     </body>
    
     </html>
    
    

    login.css

    *{
      margin: 0;
      padding: 0;
    }
    #wrap {
      height: 719px;
      width: 100;
      background-repeat: no-repeat;
      background-position: center center;
      position: relative;
    }
    #head {
      height: 120px;
      width: 100;
      background-color: #66CCCC;
      text-align: center;
      position: relative;
    }
    #foot {
      width: 100;
      height: 126px;
      background-color: #CC9933;
      position: relative;
    }
    #wrap .logGet {
      height: 408px;
      width: 368px;  
      position: absolute;
      background-color: #FFFFFF;
      top: 20%;
      right: 15%;
    }
    .logC a button {
      width: 100%;
      height: 45px;
      background-color: #ee7700;
      border: none;
      color: white;
      font-size: 18px;
    }
    .logGet .logD.logDtip .p1 {
      display: inline-block;
      font-size: 28px;
      margin-top: 30px;
      width: 86%;
    }
    #wrap .logGet .logD.logDtip {
      width: 86%;
      border-bottom: 1px solid #ee7700;
      margin-bottom: 60px;
      margin-top: 0px;
      margin-right: auto;
      margin-left: auto;
    }
    .logGet .lgD img {
      position: absolute;
      top: 12px;
      left: 8px;
    }
    .logGet .lgD input {
      width: 100%;
      height: 42px;
      text-indent: 2.5rem;
    }
    #wrap .logGet .lgD {
      width: 86%;
      position: relative;
      margin-bottom: 30px;
      margin-top: 30px;
      margin-right: auto;
      margin-left: auto;
    }
    #wrap .logGet .logC {
      width: 86%;
      margin-top: 0px;
      margin-right: auto;
      margin-bottom: 0px;
      margin-left: auto;
    }
     
     
    .title {
      font-family: "宋体";
      color: #FFFFFF;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);  /* 使用css3的transform来实现 */
      font-size: 36px;
      height: 40px;
      width: 30%;
    }
     
    .copyright {
      font-family: "宋体";
      color: #FFFFFF;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);  /* 使用css3的transform来实现 */
      height: 60px;
      width: 40%;
      text-align:center;
    }
      
     
    #foot .copyright .img {
      width: 100%;
      height: 24px;
      position: relative;
    }
    .copyright .img .icon {
      display: inline-block;
      width: 24px;
      height: 24px;
      margin-left: 22px;
      vertical-align: middle;
      background-repeat: no-repeat;
      vertical-align: middle;
      margin-right: 5px;
    }
      
    .copyright .img .icon1 {
      display: inline-block;
      width: 24px;
      height: 24px;
      margin-left: 22px;
      vertical-align: middle;
      background-repeat: no-repeat;
      vertical-align: middle;
      margin-right: 5px;
    }
    .copyright .img .icon2 {
      display: inline-block;
      width: 24px;
      height: 24px;
      margin-left: 22px;
      vertical-align: middle;
      background-repeat: no-repeat;
      vertical-align: middle;
      margin-right: 5px;
    }
    #foot .copyright p {
      height: 24px;
      width: 100%;
    }
    
    span{
      color:red;
    }


  • 相关阅读:
    datagridview中读取数据判断+考勤每月上班天数判断
    dateTimePicker日期比较+时间段内查询+员工查询薪资步骤+datagridview
    c#word 存取
    位图去空白
    过桥问题
    Dominos 2(DFS)(容器)
    poj 3421(三分)
    poj 3186(DP)
    安装Ubuntu
    poj 3273(二分)
  • 原文地址:https://www.cnblogs.com/yinxin/p/12608081.html
Copyright © 2011-2022 走看看