# thinkjs

1. this.get("xxx") #获取get传来的值
1. this.post("xxx") #获取post传来的值
1. this.success("成功") #打印成功消息
1. this.fail("-1","任务id为空") # 打印错误消息
1. this.body = "<div>6666</div>" ;//1输出html标签
1. this.ctx.type = "svg"  //设置返回类型
1. this.ctx.header['x-real-ip']   获取ip
1
2
3
4
5
6
7

# 设置/取缓存

//设置
await this.cache("name", "程国庆", {
  timeout: 24 * 60 * 60 * 1000,
});
// 获取
await this.cache("name");
// 删除
await this.cache("name", null);
1
2
3
4
5
6
7
8

# 获取配置文件里的变量

  1. config->config.js {workers:1}
  2. controller 里文件 读取 this.config('workers')

# 跨域

  1. cnpm i @koa/cors --S
  2. config-> middleware.js
const cors = require('@koa/cors');
{
    handle: cors,
    options: {}
},
1
2
3
4
5

# 封装公共方法 例子

  1. 如在根目录下创建 common->index.js
module.exports = class common {
  constructor() {}
  timeCycle(t) {
    let time = new Date(t);
    let Year = time.getFullYear(),
      Month = time.getMonth() + 1,
      Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate(),
      hour = time.getHours() < 10 ? 0 + "" + time.getHours() : time.getHours(),
      Minutes =
        time.getMinutes() < 10 ? 0 + "" + time.getMinutes() : time.getMinutes(),
      Seconds =
        time.getSeconds() < 10 ? 0 + "" + time.getSeconds() : time.getSeconds();
    Month < 10 ? (Month = 0 + "" + Month) : "";
    return (
      Year +
      "-" +
      Month +
      "-" +
      Data +
      " " +
      hour +
      ":" +
      Minutes +
      ":" +
      Seconds
    );
  }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  1. controller 里引用
const common = require("../common/index.js");
const cn = new common();
cn.timeCycle(new Date().getTime());
1
2
3

# 生成验证码

1.cnpm i svg-captcha --S

/*生成图片的js*/
var svgCaptcha = require("svg-captcha");
var codeConfig = {
  size: 4, // 验证码长度
  ignoreChars: "0o1i", // 验证码字符中排除 0o1i
  noise: 2, // 干扰线条的数量
  fontSize: 42,
  color: true, //开启文字颜色
  background: "#fff", //背景色
  width: 150,
  height: 44,
};
var captcha = svgCaptcha.create(codeConfig);
this.ctx.type = "svg"; //设置返回类型
this.cookie("captcha", captcha.text.toLowerCase()); //存到缓存里以后好做比较
this.body = captcha.data;

/*验证图形码 js*/
const captcha = await this.cookie("captcha");
console.log(captcha);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 生成 token

var jwt = require("jsonwebtoken");
/*生成token*/
let obj = {};
obj.data = data || {}; //存入token的数据
obj.ctime = new Date().getTime(); //token的创建时间
obj.expiresIn = 1000 * 60 * 60 * 12; //设定的过期时间
var token = jwt.sign(obj, "shhhhh"); // shhhhh为秘钥示例
/*解析token*/
jwt.verify(token, "shhhhh", function(err, decoded) {
  console.log(decoded);
});
1
2
3
4
5
6
7
8
9
10
11