数据库
首页 > 数据库> > 关于使用 koa路由与mysql模块, ctx.body获取不到值的问题

关于使用 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
});

更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/119816321

标签:body,function,koa,ctx,connection,json,error,var,query
来源: https://www.cnblogs.com/wangchuanxinshi/p/16352667.html