express项目改造 + 数据库操作

文章目录


express项目改造 + 数据库操作

  1. 技术栈
    ○ express
    ○ Node
    ○ ejs
    ○ MongoDB
    ○ mongoose
    ○ Common.js
    ○ restful api
    ○ Promise + async 函数

数据库的增删改查
增 add ( data ) {

  // 做数据库操作 , 添加一条数据进入数据库 
  // 4. 创建实体 【 实例化模型得到实体 】

  return new Promise(( resolve,reject ) => {

    const position = new position_model( data ) 
    // 将数据保存在了数据库
    position.save( error => {
      if( error ) {
        // 存储失败
        resolve( 0 )
      }else{
        // 表示存储成功
        resolve( 1 )
        console.log( '存储成功' ) 
      }
    }) 

  })

删del ( data ) {
return new Promise(( resolve,reject ) => {

    position_model.find( data, ( error,docs ) => {
      // [
      //   {
      //     _id: 5d36621c3d2ac544d03f3eab,
      //     positionName: 'ui',
      //     city: '北京',
      //     companyName: '千锋教育',
      //     __v: 0
      //   },
      //   {
      //     _id: 5d36627d3d2ac544d03f3eac,
      //     positionName: 'ui',
      //     city: '北京',
      //     companyName: '千锋教育',
      //     __v: 0
      //   }
      // ]


      // 一定是以一个数据 
      console.log('====================================');
      console.log( 'docs',docs );
      console.log('====================================');

      if( !(docs.length === 0) ) {
        //找到匹配的数据了 , 开始删除

        position_model.findById( docs[0]._id, ( error,result ) => {
          if( result ){
            //可以删除 
            resolve( 1 )
            result.remove()
          }else{
            // 没必要删除了
            resolve( 2 )
          }
        })

      }else{
        // 没有找到匹配的条件,不用删除
        resolve( 0 )
      }
      

    })
  })

改update ( data ) {
return new Promise(( resolve,reject ) => {

    position_model.find( data, ( error, docs ) => {
      if( !( docs.length === 0 ) ){
        //证明找到那条数据了
        position_model.findById( docs[0]._id, ( error,result ) => {
          result.city = data.city
          result.save( error => {
            if( error ) {
              resolve( 0 )
            }else{
              resolve( 1 )
            }
          })
        })
      }else{
        // 没有找到
      }
    })
  })

查 query ( data ) {
return new Promise(( resolve,reject ) => {

    if( data ){
      // 精确查找某一条
      position_model.find( data, ( error,docs ) => {
        resolve( docs )
      })
    }else{
      // 查所有的
      position_model.find({},( error,docs ) => {
        resolve( docs )
      })
    }

  })
}

用locationStorage实现自动登录

var token = localStorage.getItem(‘token’)

if( token ){
  //有
  location.href = './index.html'
}else{
  alert(  '你需要登录' )
}

}

$(’.login’).on(‘click’,function () {
$.ajax({
url: ‘http://localhost:3000/login’,
method: ‘POST’,
data: {
username: $(’.username’).val(),
password: $(’.password’).val(),
token: localStorage.getItem(‘token’)
},
success ( res ) {
const result = JSON.parse( res )
if ( result.status === 1 ) {
localStorage.setItem(‘token’,result.token)
}
}
})
})

const express = require( ‘express’ )

const fs = require( ‘fs’ )

const jwt = require( ‘jsonwebtoken’ )

const router = express.Router()

const path = require( ‘path’ )

router
.route(’/login’)
.post(( req,res,next ) => {

res.setHeader('Access-Control-Allow-Origin','*')
const { token,username,password } = req.body 

if( token ){
  //证明有值
  res.render('login',{
    data: JSON.stringify({
      info: '登录成功',
      status: 1
    })
  })
} else {
  // 第一次登录 或是 token失效 

  // 重新生成token  返回给前台
  // 1. 通过文件系统读取私钥
  let private_key=fs.readFileSync(path.join(__dirname,'../rsa/private_key.pem'))
  var use_token = jwt.sign( username, private_key,{ algorithm: 'RS256'});
  /* 
    payload: 负载也就是数据,这里是值用户名
    private_key: 通过openSSL 生成的私钥 
    RS256: 算法
  */
 res.render('login',{
   data: JSON.stringify({
     info: '登录成功',
     status: 1,
     token: use_token
   })
 })
}

})

module.exports = router

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值