关于使用 koa路由与mysql模块, ctx.body获取不到值的问题

var Koa = require('koa');
var Router = require('koa-router' );
var bodyParser = require('koa-bodyparser');
var mysql = require('mysql');
var app = new Koa();
var router = new Router();
app.use(bodyParser());

var connection = mysql.createConnection({
  host     : 'localhost',
  port:3306,
  user     : 'root',
  password : 'xxx',
  database : 'url'
});
connection.connect();


//第一类封装 ,一般用于不传递多个参数
const query = function (sql) {
    return new Promise((resolve, reject) => {
        connection.query(sql,  function (error, results) {
            if(error){
                reject(error);
            }else{
                resolve(results)
            }
        });
    })
}
//第二类封装 ,一般用于传递多个参数
const query1 = function (userStr,name,passwd,token1) {
    return new Promise((resolve, reject) => {
        connection.query(userStr,  function (error, result) {
            if(error){
                reject(error);
            }else{
                if (result.length > 0) {
                    json['message'] = '用户已经存在';
                    json['resultCode']= 1;
                } else {
                    json['message'] = '注册成功';
                    json['token'] = token1;
                    json['resultCode'] = 200;
                    var insertStr = `insert into login (username, password,token) values ("${name}", "${passwd}","${token1}")`;
                    console.log(insertStr)
                    connection.query(insertStr, function (err, res) {
                        if (err) throw err;
                    })
                }
                resolve(json)
            }
        });
    })
}


// 使用第一类封装
router.get( '/csdnurl', async(ctx, next) => {
    var sql = "select * from csdnurl";
    let results = await query(sql);
    ctx.body=results
});
// 使用第一类封装
router.post('/login', async (ctx, next) => {
    var name = ctx.request.body.username;
    var passwd = ctx.request.body.password;
    var userStr = `select username,password,token from login where username="${name}" and password="${passwd}"`;
    let results = await query(userStr);
    ctx.body = results
});

// 使用第二类封装
router.post('/register', async (ctx, next) => {
    var name = ctx.request.body.username;
    var passwd = ctx.request.body.password;
    var token1 = jwt.sign({
        username: name
    }, secretkey, {
        expiresIn: 60 * 8
    });
    var userStr = `select * from login where username="${name}"`;
    let results = await query1(userStr,name,passwd,token1);
    ctx.body = json
});

这里主要使用了 asyncawait 处理异步问题

作者:Vam的金豆之路

主要领域:前端开发

我的微信:maomin9761

微信公众号:前端历劫之路