NodeJS 使用内容以及模拟一个接口

1.结合上一篇 安装完Nodejs之后 通过手动创建一个完整的NodeJs项目

2.https://www.jianshu.com/p/7b0a5d4491ba 创建一个完整的项目之后

3.下面是一个完整的项目结构

 

3.在routes下面新建一个目录为mysql--mysql.js

var mysql = require('mysql');
var dbMsg = {
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : '数据库名称'
}
 
 
var connection = mysql.createConnection(dbMsg);
    connection.connect();
module.exports = connection;

 

 

 

4. 配置路由

ar loginRouter = require('./routes/login');
 
 
app.use('/login', loginRouter);

 

 

 

5.在routes文件夹下面创建一个login.js

var express = require('express');
var URL = require('url');
var router = express.Router();
var connection = require('./mysql/mysql');
 
 
 
router.post('/user',function(req, res, next){
  var params = {
    username : req.query.username,
    password : req.query.password
  }
  var userStr = 'select * from user_info_t where login_name=? and password=?';
  var str = [params.username,params.password];
  console.log(userStr)
  connection.query(userStr,str,function(err,result){
        if(err){
            throw err;
        }else{
            res.send(result)
        }
    })
});
 
 
 
router.get('/', function(req, res, next) {
 
  var user = {
    name:'',
    age:'',
    city:''
  };
  var params = URL.parse(req.url, true).query;
 
  if(params.id == '1') {
    user.name = "Mr.light";
    user.age = "1";
    user.city = "深圳市";
  } else {
    user.name = "Ms.lee";
    user.age = "2";
    user.city = "广东市";
  }
  var response = {status:1,data:user};
  res.send(JSON.stringify(response))
});
 
 
 
 
module.exports = router;

 

启动bin下面的www文件 node www

6.浏览器输入http://127.0.0.1:3000/login

注意:记得安装 npm install mysql 模块

至此一个接口就这样完成了

 

实现登陆拦截 以及注册等基础功能 上代码

前端两个页面 login.ejs  register.ejs index.ejs

<!DOCTYPE html>
<html>
  
<head>
    <meta charset="utf-8">
    <title>登录界面</title>
    <link rel="stylesheet" href="css/reset.css" />
    <link rel="stylesheet" href="css/common.css" />
    <link rel="stylesheet" href="css/font-awesome.min.css" />
  </head>
  <body>
    <div class="wrap login_wrap">
      <div class="content">
        <div class="logo"></div>
        <div class="login_box">  
          
          <div class="login_form">
            <div class="login_title">
              登录
            </div>
              <div class="form_text_ipt">
                <input name="username" id="username" type="text" placeholder="手机号/邮箱">
              </div>
              <div class="ececk_warning"><span>手机号/邮箱不能为空</span></div>
              <div class="form_text_ipt">
                <input name="password" id="password" type="password" placeholder="密码">
              </div>
              <div class="ececk_warning"><span>密码不能为空</span></div>
              <div class="form_check_ipt">
                <div class="left check_left">
                  <label><input name="" type="checkbox"> 下次自动登录</label>
                </div>
                <div class="right check_right">
                  <a href="#">忘记密码</a>
                </div>
              </div>
              <div class="form_btn">
                <button type="button" οnclick="login();">登录</button>
              </div>
              <div class="form_reg_btn">
                <span>还没有帐号?</span><a href="register">马上注册</a>
              </div>
            <div class="other_login">
              <div class="left other_left">
                <span>其它登录方式</span>
              </div>
              <div class="right other_right">
                <a href="#"><i class="fa fa-qq fa-2x"></i></a>
                <a href="#"><i class="fa fa-weixin fa-2x"></i></a>
                <a href="#"><i class="fa fa-weibo fa-2x"></i></a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <script type="text/javascript" src="js/jquery-3.3.1.min.js" ></script>
    <script type="text/javascript" src="js/common.js" ></script>
    <div style="text-align:center;">
</div>
 
<script>
  function check(username,password){
    if(username==''){
      alert('用户名不能为空')
      return false;
    }
    if(password==''){
      alert('密码不能为空')
      return false;
    }
    return true;
  }
  
  function login () {
    var username = $('#username').val();
    var password = $('#password').val();
    var params = ({
      username: username,
      password : password
    })
    if(check(username,password)){
      $.ajax({
        type:"post",
        url:"/login/login",
        async:true,
        data:params,
        success:function(data){
          if(data.code=='1'){
            alert('用户名或密码错误')
          }else{
            location.href='/index';
          }
        }
      });
    }
  }
</script>
  </body>
</html>

 

 

register

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>注册界面</title>
    <link rel="stylesheet" href="css/reset.css" />
    <link rel="stylesheet" href="css/common.css" />
    <link rel="stylesheet" href="css/font-awesome.min.css" />
  </head>
  <body>
    <div class="wrap login_wrap">
      <div class="content">
        
        <div class="logo"></div>
        
        <div class="login_box">  
          
          <div class="login_form">
            <div class="login_title">
              注册
            </div>
              
              <div class="form_text_ipt">
                <input name="username" id="username" type="text" placeholder="手机号/邮箱">
              </div>
              <div class="ececk_warning"><span>手机号/邮箱不能为空</span></div>
              <div class="form_text_ipt">
                <input name="password" id="password" type="password" placeholder="密码">
              </div>
              <div class="ececk_warning"><span>密码不能为空</span></div>
              <div class="form_text_ipt">
                <input name="repassword" id="repassword" type="password" placeholder="重复密码">
              </div>
              <div class="ececk_warning"><span>密码不能为空</span></div>
              <!--<div class="form_text_ipt">
                <input name="code" type="text" placeholder="验证码">
              </div>-->
              <div class="ececk_warning"><span>验证码不能为空</span></div>
              
              <div class="form_btn">
                <button type="button" οnclick="register();">注册</button>
              </div>
              <div class="form_reg_btn">
                <span>已有帐号?</span><a href="/">马上登录</a>
              </div>
            <div class="other_login">
              <div class="left other_left">
                <span>其它登录方式</span>
              </div>
              <div class="right other_right">
                <a href="#"><i class="fa fa-qq fa-2x"></i></a>
                <a href="#"><i class="fa fa-weixin fa-2x"></i></a>
                <a href="#"><i class="fa fa-weibo fa-2x"></i></a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <script type="text/javascript" src="/js/jquery-3.3.1.min.js" ></script>
    <script type="text/javascript" src="js/common.js" ></script>
    <div style="text-align:center;">
</div>
<script>
  function register(){
    var password = $('#password').val();
    var username = $('#username').val();
    var repassword = $('#repassword').val();
    
    var params = ({
      password: password,
      username: username
    })
    if(check(username,password,repassword)){
      $.ajax({
        type:"post",
        url:"/login/register",
        data:params,
        dataType:'json',
        success:function(data){
          if(data.code=="0"){
            alert('注册成功请登录');
            window.location.href="/";
          }
        }
      });
    }
    
  }
  
  function check(username,password,repassword){
    if(username==''){
      alert('手机号不能为空!')
      return false;
    }
    
    if(password =='' || repassword==''){
      alert('密码不能为空!')
      return false;
    }
    
    if(password!=repassword){
      alert('两次密码不一致!')
      return false;
    }
    
    return true;
  }
</script>
  </body>
</html>

 

 

index.ejs

 

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <script src="/js/jquery-3.3.1.min.js"></script>
    <script  src="/js/vue/dist/vue.js"></script>
    <script  src="/js/vue-spinner/dist/vue-spinner.min.js"></script>
 
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
    
    <div id="app">
      <button type="button" @click="ajax()">获取参数</button>
      <br>
      <br>
      <br>
      <table border="1">
        <tr>
          <td>id</td>
          <td>年龄</td>
          <td>电话</td>
          <td>姓名</td>
        </tr>
        <template v-for="(items,index) in data">
          <tr>
          <td>{{items.id}}</td>
          <td>{{items.age}}</td>
          <td>{{items.phone_number}}</td>
          <td>{{items.user_name}}</td>
        </tr>
        </template>
      </table>
    </div>
    
    <script>
      var queryWarnReportData = function (params, callback) {
        $.ajax({
            method: "get",
            url: '/query',
            data: params,
            success: callback,
            error: function (response) {
                console.error(response)
            }
        });
    }
</script>
    
    <script>
       var defaultParams={};
    var PulseLoader = VueSpinner.PulseLoader;
    var app = new Vue({
        el: '#app',
        data: {
            queryParams: defaultParams,
            data: {
                pageNum:0,
                pages:0,
            },
            show: true,
            color: '#43A5C9',
        },
        components: {
            PulseLoader
        },
        methods: {
            updateData: () => {
            Vue.set(app, 'show', true);
            queryWarnReportData(app.queryParams, (data) => {
                Vue.set(app, 'show', false);
                Vue.set(app, 'data', data);
            })
    },ajax:()=>{
      var params = ({
          username : 'admin',
          password : '25b7f5afee0d962a'
        });
        $.ajax({
          type:"post",
          url:"/login/user",
          data:params,
          dataType:"json",
          success:function(data){
            var str = '';
            $.each(data, function(index,obj) {
              console.log(obj.id);
            });
          }
        });
    },
    },
    created: () => queryWarnReportData(defaultParams, (data) => {
        Vue.set(app, 'show', false);
        Vue.set(app, 'data', data);
    }),
    });
</script>
  </body>
</html>

 

 

配置拦截 app.js

npm install express-session    下载模块

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');
 
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var loginRouter = require('./routes/login');
var queryRouter = require('./routes/query');
var app = express();
 
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
 
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
 
 
app.use(cookieParser());
app.use(session({
    resave: true, // don't save session if unmodified
    saveUninitialized: false, // don't create session until something stored
    secret: 'admin', //密钥
    name: 'testapp', //这里的name值得是cookie的name,默认cookie的name是:connect.sid
    cookie: {
        maxAge: 80000
    } //设置maxAge是80000ms,即80s后session和相应的cookie失效过期
}));
 
 
//登录拦截器
app.use(function (req, res, next) {
  var url = req.originalUrl;
console.log("session"+req.session.user)
  if (url != "/login/login" && url != "/login/register" && url != "/" &&!req.session.user) {
      return res.redirect("/");
  }
  next();
});
 
 
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/login', loginRouter);
app.use('/query', queryRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});
 
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
 
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
 
 
 
 
module.exports = app;

 

 

session 存放  login.js

var express = require('express');
var URL = require('url');
var router = express.Router();
var connection = require('./mysql/mysql');
var bodyParser = require('body-parser');
var session = require('express-session');
router.use(bodyParser.urlencoded({extended:false}));
 
router.post('/login',function(req, res, next){
  var params = {
    username : req.body.username,
    password : req.body.password
  }
  var userStr = 'select * from sys_user where login_name=? and password=md5(?)';
  var str = [params.username,params.password];
  
  connection.query(userStr,str,function(err,user){
        if(!user[0]){
            res.send({error:'用户名或密码错误!','code':'1'})
        }else{
          req.session.user = user[0];
          console.log(req.session.user)
           res.send({error:'登陆成功!','code':'0'})
        }
    })
});
 
 
 
router.get('/query', function(req, res, next) {
 
  var user = {
    name:'',
    age:'',
    city:''
  };
  var params = URL.parse(req.url, true).query;
 
  if(params.id == '1') {
    user.name = "Mr.light";
    user.age = "1";
    user.city = "深圳市";
  } else {
    user.name = "Ms.lee";
    user.age = "2";
    user.city = "广东市";
  }
  var response = {status:1,data:user};
  res.send(JSON.stringify(response))
});
 
 
 
//用户注册
 
 
router.post('/register', function(req, res, next) {
  var params = {
    username : req.body.username,
    password : req.body.password
  }
  var userStr = 'insert into sys_user (login_name,phone_number,password,create_time,user_name) values (?,?,md5(?),now(),?)';
  var str = [params.username,params.username,params.password,params.username];
  
  connection.query(userStr,str,function(err,result){
        if(err){
            throw err;
        }else{
          var datas = {'code':'0','msg':'注册成功'};
            res.send(datas)
        }
    })
});
 
module.exports = router;

 

 

index.js

var express = require('express');
var router = express.Router();
 
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('login', { title: 'Express' });
});
 
router.get('/register', function(req, res, next) {
  res.render('register', { title: 'Express' });
});
 
router.get('/index', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
 
module.exports = router;

 

 

源码地址:https://gitee.com/qwerdfs/nodejs_development

posted @ 2019-09-10 09:20 小__伟 阅读(...) 评论(...) 编辑 收藏