Initialize the project
1. UseMakdir Folder name
Create a folder
For example,
Makdir koa_start CD koa_start then run NPM initCopy the code
2. InstallKoa, KOA-Router, KoA-CORS, KoA-BodyParser,mysql
NPM install koa, koa-router, koa-cors, koa-bodyparse,mysql --saveCopy the code
Koa-router is the routing file, KOA-Cors is the backend cross-domain group price, and koA-bodyParse is the intermediate key for post value acceptance
2. New app. Js
/ / server. Js file
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); // Query the database
if (result.status == 200) {
if(result.results.length>0){
ctx.body = {
code: 200.token: "7987asdjabsdqweqwesdqwewqe"}; }else{
ctx.body = {
code: 400.message: "Wrong username and password, please re-enter"}; }}else if (result.status == 400) {
ctx.body = {
code: 401.message: "Connection error, please try again."}; }else{
ctx.body = {
code: 500.message: "Server connection failed"}; }}); app.use(cors());// Connect the KOA to the two middleware
app.use(router.routes()).use(router.allowedMethods());
// Listen on port 3001
app.listen(3001.() = >{
console.log('server is alerday start')});Copy the code
app.use(bodyParser()); To convert the request parameters in the POST request
So post gets the front end request as let ctx_query = ctx.request.body; Get gets the request parameter as let ctx_query = ctx.query;
3. Create the dbconfig.js database configuration
dbconfig.js
module.exports = {
config: {
db_host: "localhost", -- Host namedb_port: "3306", -- Host portdb_name: "test", -- database namedb_user: "root", -- database login namedb_passwd: "root"-- database connection password},};Copy the code
4. Create the mysqlDB database connection file
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, "database connection failed ");
resolve({
status: 500}); }else {
//console.log(" Database connection succeeded ");
connection.query(sql, values, (err, results) = > {
if (err) {
reject(err);
resolve({
status: 400
});
} else {
connection.release();
resolve({
status: 200,
results,
});
}
Connection.release () // Releases the connection pool}); }})})}Copy the code
5. Start the project
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": "Tokens ^ 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." "}}Copy the code
NPM run start Starts the projectCopy the code
Then listen on port 3001 on the browser and the server starts