4.5.0 • Published 10 months ago

koa-jwtdd v4.5.0

Weekly downloads
-
License
ISC
Repository
-
Last release
10 months ago

koa2.router

NPM version Build status Test coverage Dependency Status License Downloads

Koa2.router file serving middleware, wrapper for koa-send.

Installation

$ npm install koa-jwtdd

API

// app
const Koa = require('koa');
const app = new Koa();
const router=require('./app/router/router');
const od=require('./app/router/od');
const {koaBody}=require('koa-body');
var jwt = require('koa-jwt');
const {secret,jiekou}=require('./app/util/jq');
const static=require('koa-static');
const path=require('path');
const mount=require('koa-mount');
app.use(mount('/myweb',static(path.resolve(__dirname,'./app/public'))));
app.use(jwt({ secret: secret}).unless({ path:jiekou }));
app.use(koaBody());
app.use(router);
app.use(od);
app.listen(3000,()=>{console.log('服务启动成功');});
  • root root directory string. nothing above this root directory can be served
  • opts options object.

Options

  • maxage Browser cache max-age in milliseconds. defaults to 0
  • hidden Allow transfer of hidden files. defaults to false
  • index Default file name, defaults to 'index.html'
  • defer If true, serves after return next(), allowing any downstream middleware to respond first.
  • gzip Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true.
  • br Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists (note, that brotli is only accepted over https). defaults to true.
  • setHeaders Function to set custom headers on response.
  • extensions Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false)

Example

// controller
// login
const user=require('../service/user');
const {secret}=require('../util/jq');
const jwt=require('jsonwebtoken');
const {jia,jie}=require('../util/bcrypt');
const emzhuche=async(ctx,next)=>{
    let {email,password}=ctx.request.body;
    let arr=await user.cha({email});
    if(arr && arr.length){ctx.throw(400,'邮箱已存在')}
    let zz=/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    if(zz.test(email)){
        let jiami=jia(password);
        let arr1=await user.zeng({email,'password':jiami});
        ctx.body={
            code:200,
            msg:'注册成功',
            arr1}}else{
        ctx.throw(400,'邮箱错误')}}
const emdenglu=async(ctx,next)=>{
    let {email,password}=ctx.request.body;
    let arr=await user.cha({email});
    if(arr && !arr.length){
        ctx.body={code:400,msg:'邮箱错误'}}
    let jm=jie(password,arr[0].password);
    if(jm){
        ctx.body={code:400,msg:'密码错误'}}
    const token=jwt.sign({
        email,password,emailid:arr[0].emailid,},secret, { expiresIn: '24h' });
      ctx.body={code:400,msg:'登录成功',token,}}
module.exports = {
    emzhuche,
    emdenglu,
}stening on port 3000')'

Options

  • maxage Browser cache max-age in milliseconds. defaults to 0
  • hidden Allow transfer of hidden files. defaults to false
  • index Default file name, defaults to 'index.html'
  • defer If true, serves after return next(), allowing any downstream middleware to respond first.
  • gzip Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true.
  • br Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists (note, that brotli is only accepted over https). defaults to true.
  • setHeaders Function to set custom headers on response.
  • extensions Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false)

Example

// od
const user=require('../service/od');const chaxun=async(ctx,next)=>{
    let arr =await user.cha({});
    if(arr && arr.length){
        ctx.body={code:200,msg:'查询成功',arr }
    }else{
        ctx.body={code:200,msg:'暂无数据',}}}

const zengjia=async(ctx,next)=>{
    let {price,title}=ctx.request.body;
    let arr=await user.zeng({price,title});
    if(arr){
        ctx.body={code:200,msg:'添加成功',arr}}}

const shanchu=async(ctx,next)=>{
    let {goodsid,goodstype}=ctx.request.body;
    if(goodstype ==1001){
        let arr=await user.shan({goodsid});
        if(arr){
            ctx.body={code:200,msg:'删除成功', arr}}
    }else{
        ctx.body={code:200,msg:'未签收不能删除',}}}

const xiugai=async(ctx,next)=>{
    let {price,goodsid}=ctx.request.body;
    let arr=await user.gai({price,goodsid});
    if(arr){
        ctx.body={code:200,msg:'修改成功',arr}}}
//shengxujiangxu
const paix=async(ctx,next)=>{
    let {jg}=ctx.query;
    let arr=await oder.sxu({});
    let arr1=await oder.jxu({})
    switch(jg){
        case'0':{
            ctx.body={code:200,arr,arr1} break}
        case'1':{
            ctx.body={code:200,arr} break}
        case'2':{
            ctx.body={code:200,arr1} break}}}

//duotiaojianchaxun
const duocha=async(ctx,next)=>{
    let pm=ctx.query;
    let arr =await user.cha1(pm);
    ctx.body={code:200,arr,}}
//duobiaoliancha
const duobiaocha=async(ctx,next)=>{
    let {goodsid}=ctx.query;
    let arr =await user.duobiao({goodsid});
    if(arr){
        ctx.body={code:200,arr,}} }
module.exports = {
    chaxun,zengjia,shanchu,xiugai,duocha,duobiaocha,paix}

Options

  • maxage Browser cache max-age in milliseconds. defaults to 0
  • hidden Allow transfer of hidden files. defaults to false
  • index Default file name, defaults to 'index.html'
  • defer If true, serves after return next(), allowing any downstream middleware to respond first.
  • gzip Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true.
  • br Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists (note, that brotli is only accepted over https). defaults to true.
  • setHeaders Function to set custom headers on response.
  • extensions Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false)

Example

// service
// od
const query=require('../db/query');

const cha=()=>{let sql=`SELECT * FROM goods_tab`;return query(sql);}
const zeng=({price,title})=>{let sql=`INSERT INTO goods_tab (price,title) VALUES ('${price}','${title}')`;return query(sql);}
const shan=({goodsid})=>{let sql=`DELETE FROM goods_tab WHERE goodsid = '${goodsid}'`;return query(sql);}
const gai=({price,goodsid})=>{let sql=`UPDATE goods_tab SET price ='${price}' WHERE goodsid = ${goodsid}`;return query(sql);}
const sxu=({jg})=>{let sql=`SELECT * FROM goods_tab ORDER BY jg LIMIT 0,1000`;return query(sql);}
const jxu=({jg})=>{let sql=`SELECT * FROM goods_tab ORDER BY jg DESC LIMIT 0,1000`;return query(sql);}
//duotiaojianchaxiu
const cha1=(pm)=>{let sql=`SELECT * FROM goods_tab `;
    if(pm?.goodsid || pm?.title || pm?.goodstype){sql+=` where`}
    if(pm?.goodsid){sql+=` goodsid='${pm.goodsid}' `}
    if(pm?.goodstype){sql+=` goodstype='${pm.goodstype}' `}
    if(pm?.title){sql+=` title='${pm.title}' `}
    //fenye
    if(pm?.page && pm?.count){sql+=` limit ${(pm.page-1)*pm.count},${pm.count}`}
    //mohuchaxun
    if (pm?.title ) {sql += ` title like '%${pm.title}%' `}
    console.log(sql);
    return query(sql);
}

//duobiaoliancha

const duobiao=({goodsid,goodstype})=>{let sql=`select * from goods_tab as t1 `;
    sql+=` inner join pingl_tab as t2 on t1.goodsid = t2.goodsid `
    sql+=` inner join pingp_tab as t3 on t1.pingpid = t3.pingpid `
    sql+=` where t1.goodsid=${goodsid}`
    return query(sql);}
module.exports = {cha,zeng,shan,gai,cha1,duobiao,sxu,jxu,}

Options

  • maxage Browser cache max-age in milliseconds. defaults to 0
  • hidden Allow transfer of hidden files. defaults to false
  • index Default file name, defaults to 'index.html'
  • defer If true, serves after return next(), allowing any downstream middleware to respond first.
  • gzip Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true.
  • br Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists (note, that brotli is only accepted over https). defaults to true.
  • setHeaders Function to set custom headers on response.
  • extensions Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false)

Example

// service 
// user
const query=require('../db/query');

const cha=({email})=>{
    let sql=`SELECT * FROM email where email='${email}'`
    console.log(sql);
    return query(sql);}

const zeng=({email,password})=>{
    let sql=`INSERT INTO email (email,password) VALUES ('${email}','${password}')`
    console.log(sql);
    return query(sql);}
module.exports = {cha,zeng,}

Options

  • maxage Browser cache max-age in milliseconds. defaults to 0
  • hidden Allow transfer of hidden files. defaults to false
  • index Default file name, defaults to 'index.html'
  • defer If true, serves after return next(), allowing any downstream middleware to respond first.
  • gzip Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true.
  • br Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists (note, that brotli is only accepted over https). defaults to true.
  • setHeaders Function to set custom headers on response.
  • extensions Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false)

Example

// router
// od
const Router = require('koa2-router');
const router = new Router();
const od=require('../controller/od');
router.get('/chaxun',od.chaxun);
router.post('/zengjia',od.zengjia);
router.post('/shanchu',od.shanchu);
router.post('/xiugai',od.xiugai);
router.get('/duocha',od.duocha);
router.get('/duobiaocha',od.duobiaocha);
router.get('/paix',od.paix);
module.exports = router 
// router
const Router = require('koa2-router');
const router = new Router();
const login=require('../controller/login');
router.post('/emzhuche',login.emzhuche);
router.post('/emdenglu',login.emdenglu);
module.exports = router 

Options

  • maxage Browser cache max-age in milliseconds. defaults to 0
  • hidden Allow transfer of hidden files. defaults to false
  • index Default file name, defaults to 'index.html'
  • defer If true, serves after return next(), allowing any downstream middleware to respond first.
  • gzip Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true.
  • br Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists (note, that brotli is only accepted over https). defaults to true.
  • setHeaders Function to set custom headers on response.
  • extensions Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false)

Example

// indexhtml
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="box"></div>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    function xuanran(data) {
        let box = document.querySelector('.box');
        box.innerHTML = data.map(item => {
            return `${item.goodsid},${item.goodstype},${item.price},${item.title},<br>`
        }).join('');
    }

    axios.post('/chaxun', {

    }).then(function (response) {
            console.log(response);
            xuanran(response.data.arr);
        })
        .catch(function (error) {
            console.log(error);
        });
</script>

</html>

Options

  • maxage Browser cache max-age in milliseconds. defaults to 0
  • hidden Allow transfer of hidden files. defaults to false
  • index Default file name, defaults to 'index.html'
  • defer If true, serves after return next(), allowing any downstream middleware to respond first.
  • gzip Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true.
  • br Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists (note, that brotli is only accepted over https). defaults to true.
  • setHeaders Function to set custom headers on response.
  • extensions Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false)

Example

// login
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    账号:<input type="text" class="inp1"><br>
    密码:<input type="text" class="inp2">
    <button class="btn1">注册</button><button class="btn2">登录</button>
</body>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>
    let btn1 = document.querySelector('.btn1');
    let btn2 = document.querySelector('.btn2');
    btn1.onclick = function () {
        let inp1 = document.querySelector('.inp1');
        let inp2 = document.querySelector('.inp2');
        let aa=inp1.value;
        let bb=inp2.value;
        const zz=/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
        if(zz.test(aa)){
            axios.post('/emzhuche', {
            email:aa,
            password:bb,
        })
            .then(function (response) {
                console.log(response);
                alert('注册成功')
            })
            .catch(function (error) {
                console.log(error);
                alert('注册失败')
            });
        }else{
            alert('邮箱格式错误')
            return
        }}
    btn2.onclick = function () {
        let inp1 = document.querySelector('.inp1');
        let inp2 = document.querySelector('.inp2');
        let aa=inp1.value;
        let bb=inp2.value;
        axios.post('http://localhost:3000/emdenglu', {
            email:aa,
            password:bb,
        })
            .then(function (response) {
                console.log(response);
                alert('登录成功')
            })
            .catch(function (error) {
                console.log(error);
                alert('登录失败')
            });}
</script>

</html>

Options

  • maxage Browser cache max-age in milliseconds. defaults to 0
  • hidden Allow transfer of hidden files. defaults to false
  • index Default file name, defaults to 'index.html'
  • defer If true, serves after return next(), allowing any downstream middleware to respond first.
  • gzip Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true.
  • br Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists (note, that brotli is only accepted over https). defaults to true.
  • setHeaders Function to set custom headers on response.
  • extensions Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false)

Example

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

Options

  • maxage Browser cache max-age in milliseconds. defaults to 0
  • hidden Allow transfer of hidden files. defaults to false
  • index Default file name, defaults to 'index.html'
  • defer If true, serves after return next(), allowing any downstream middleware to respond first.
  • gzip Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true.
  • br Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists (note, that brotli is only accepted over https). defaults to true.
  • setHeaders Function to set custom headers on response.
  • extensions Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false)

Example

// util bcryptjs
var bcrypt = require('bcryptjs');

const jia = (password) => {
    var salt = bcrypt.genSaltSync(10);
    var hash = bcrypt.hashSync(password, salt);
    return hash}
const jie=(password,hash)=>{
    return bcrypt.compareSync(password, hash);}
module.exports = {jia,jie}

Options

  • maxage Browser cache max-age in milliseconds. defaults to 0
  • hidden Allow transfer of hidden files. defaults to false
  • index Default file name, defaults to 'index.html'
  • defer If true, serves after return next(), allowing any downstream middleware to respond first.
  • gzip Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true.
  • br Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists (note, that brotli is only accepted over https). defaults to true.
  • setHeaders Function to set custom headers on response.
  • extensions Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false)

Example

const secret='secret';
const jiekou=['/jianyi','/jiayi','/duobiaocha','/duocha','/xiugai','/shanchu','/zengjia','/chaxun','/emdenglu','/emzhuche',/\/myweb/];

module.exports = {secret,jiekou}

Options

  • maxage Browser cache max-age in milliseconds. defaults to 0
  • hidden Allow transfer of hidden files. defaults to false
  • index Default file name, defaults to 'index.html'
  • defer If true, serves after return next(), allowing any downstream middleware to respond first.
  • gzip Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true.
  • br Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists (note, that brotli is only accepted over https). defaults to true.
  • setHeaders Function to set custom headers on response.
  • extensions Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false)

Example

Options

  • maxage Browser cache max-age in milliseconds. defaults to 0
  • hidden Allow transfer of hidden files. defaults to false
  • index Default file name, defaults to 'index.html'
  • defer If true, serves after return next(), allowing any downstream middleware to respond first.
  • gzip Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true.
  • br Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists (note, that brotli is only accepted over https). defaults to true.
  • setHeaders Function to set custom headers on response.
  • extensions Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false)

Example

See also

License

MIT