koa项目创建完成后
测试数据库能否正常连接
const mysql = require('mysql') const pool = mysql.createPool({ host: '127.0.0.1', user: 'root', password: '123456', database: 'mytest', port: 3306 }) const query = (sql, values) => { return new Promise((resolve, reject) => { pool.getConnection((err, conn) => { if (err) { reject(err) } else { conn.query(sql, values, (err, res) => { if (err) { reject(err) } else { resolve(res[0]) } conn.release() }) } }) }) } async function queryAll(sql, values) { return await query(sql, values) } module.exports = queryAll
数据库最好是utf-8格式的,其他都可以默认
如果你要用token
npm i koa-jwt jsonwebtoken
在app.js中指定不用token的URL,其他的URL都要用你生成的token,postman测试
如果能返回数据,那么你的token就没问题了
app.use( koajwt({ secret: 'xiaodunmeng' }).unless({ path: [/^\/users\/login/] }) )
登录的时候获取token
const router = require('koa-router')() const queryAll = require('../db/index') const resData = require('../utils/resData') const jwt = require('jsonwebtoken') router.prefix('/users') router.get('/login', async (ctx, next) => { const { username, password } = ctx.request.query const sql = 'select * from user where username=? and password=?' const res = await queryAll(sql, [username, password]) if (res) { const token = jwt.sign( { foot: 'xiao' }, 'xiaodunmeng', { expiresIn: '1h' } ) res.token = token ctx.body = resData.success(res) } else { ctx.body = resData.fail('账号或密码不正确') } }) module.exports = router
resData.js 封装一下,写起来简单一点
const CODE = { SUCCESS: 200, PARAM_ERROR: 10001, // 参数错误 USER_ACCOUNT_ERROR: 20001, //账号或密码错误 USER_LOGIN_ERROR: 30001, // 用户未登录 BUSINESS_ERROR: 40001, //业务请求失败 AUTH_ERROR: 500001 // 认证失败或TOKEN过期 } module.exports = { success(data = '', msg = '请求成功', code = CODE.SUCCESS) { return { code, data, msg } }, fail(msg = '请求失败', data = '', code = CODE.USER_ACCOUNT_ERROR) { return { code, data, msg } } }
完成后配合前端,就能写基本的接口了