menu 山水有轻音
more_vert
koa+mysql搭建服务端
2021-01-22 | 后端 | 暂无评论 | 22 次阅读 | 227字

一、初始化项目

1.使用makdir 文件夹名创建一个文件夹

例如

makdir koa_start
cd koa_start
然后执行 npm init

2.安装 koa、 koa-router、 koa-cors、 koa-bodyparser,mysql

npm install koa,koa-router, koa-cors,koa-bodyparse,mysql --save

koa-router是路由文件,koa-cors是后端跨域组价,koa-bodyparse是post传值接受的中间键

2.新建app.js

// server.js文件

let Koa = require("koa");
let Router = require("koa-router");
let cors = require("koa-cors");
const bodyParser = require("koa-bodyparser");
let fs = require("fs");
const app = new Koa();
app.use(bodyParser());
const router = new Router();
const db = require("./mysqlDB");
router.post("/user/login", async (ctx,next) => {
  let ctx_query = ctx.request.body;
  let sql = `select * from users where user='${ctx_query.username}' and passwd='${ctx_query.password}'`;
  const result = await db.query(sql); //查询数据库
    if (result.status == 200) {
      if(result.results.length>0){
         ctx.body = {
           code: 200,
           token: "7987asdjabsdqweqwesdqwewqe",
         };
      }else{
          ctx.body = {
            code: 400,
            message: "用户名和密码错误,请重新输入",
          };
      }
    } else if (result.status == 400) {
       ctx.body = {
         code: 401,
         message: "连接错误,请重新再试",
       };
    }else{
      ctx.body = {
        code: 500,
        message: "服务器连接失败",
      };
    }
});

app.use(cors());
// 将koa和两个中间件连起来
app.use(router.routes()).use(router.allowedMethods());
// 监听3001端口
app.listen(3001,()=>{
    console.log('server is alerday start')
});

app.use(bodyParser());是为了在post请求中转化得到请求参数的

所以post得到前端请求的参数为 let ctx_query = ctx.request.body;
get得到请求的参数为let ctx_query = ctx.query;

3.新建dbconfig.js数据库的配置

dbconfig.js
module.exports = {
  config: {
    db_host: "localhost", --主机名
    db_port: "3306",      --主机端口
    db_name: "test",      --数据库名
    db_user: "root",      --数据库登录名
    db_passwd: "root"     --数据库连接密码
  },
};

4.新建mysqlDB数据库连接文件

mysqlDB.js
const mysqlDb = require("mysql");
const config = require("./dbconfig");
let options = {
  host: config.config.db_host,
  user: config.config.db_user,
  password: config.config.db_passwd,
  database: config.config.db_name,
  multipleStatements: true,
};
 var pool = mysqlDb.createPool(options);
 exports.query = function (sql, values) {
    return new Promise((resolve, reject) => {
      pool.getConnection(function (err, connection) {
        if (err) {
          reject(err)
          //console.log(err, "数据库连接失败");
          resolve({
            status: 500,
          });
        } else {
          //console.log("数据库连接成功");
          connection.query(sql, values, (err, results) => {
            if (err) {
              reject(err);
              resolve({
                status: 400
              });
            } else {
              connection.release();
              resolve({
                status: 200,
                results,
              });
            }
            //connection.release() // 释放连接池
          });
        }
      })
    })
  }

5、启动项目

package.json里面配置

{
  "name": "koa-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node ./app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "koa": "^2.13.1",
    "koa-bodyparser": "^4.3.0",
    "koa-cors": "0.0.16",
    "koa-router": "^10.0.0",
    "mysql": "^2.18.1",
    "save": "^2.4.0"
  }
}

npm run start启动项目

然后在浏览器是上监听3001端口,服务器就启动了

发表评论
暂无评论
textsms
account_circle
email
link