关于使用 koa路由与mysql模块, ctx.body获取不到值的问题
阅读原文时间:2023年07月09日阅读:2

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

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章