Koa quick installation begins
NPM install koa // Install koa-router NPM install koa-router // install koa-body NPM install Koa-body // Parse request.body // Install nodemon NPM install -g nodemonCopy the code
Create a new app.js
const Koa = require("koa")
const Router = require("koa-router")
const koabody = require("koa-body")
// instantiate app
const app = new Koa()
const router = new Router()
router.get("/".ctx= > {
ctx.body = "1111"
})
app.use(koabody())
app.use(router.routes()).use(router.allowedMethods())
app.listen(2000.() = > {
console.log("Monitoring port number");
})
Copy the code
Create the server in package.json and run it directly
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"."server":"nodemon app.js"
},
Copy the code
Remotely connect to the mongodb database
/ / install the mongoose
npm install mongoose
Copy the code
Add the mongodb Key to the config key. js folder
module.exports = {
Url: "/ / key secret"
}
Copy the code
app.js
const mongoose = require("mongoose")
const url = require("./config/key").Url
// Link the database
mongoose.connect(url, { useNewUrlParser: true })
.then(() = > {
console.log("Mongoose link successful");
})
.catch(err= > {
console.log('Connection error' + err);
})
// The terminal displays whether the connection is up
Copy the code
Create a new router folder for users.js
const Router = require("koa-router")
const router = new Router()
router.get("/text".async ctx => {
ctx.status = 200
ctx.body = { msg: "text"}})module.exports = router.routes()
Copy the code
app.js
const users = require("./router/users")
router.use("/api", users)
app.use(router.routes()).use(router.allowedMethods())
Copy the code
The new models
const mongoose = require("mongoose")
const Schema = mongoose.Schema
// Instantiate a data template
const template = new Schema({
name: { type: String.required: true },
sex: { type: String.required: true },
data: { type: String.required: true}})module.exports = mongoose.model("user", template)
Copy the code
/router/users.js
const Router = require("koa-router")
const router = new Router()
const User = require(".. /models/User") / / introduced models/user
router.get("/text".async ctx => {
ctx.status = 200
ctx.body = { msg: "text"}})// Store to database
router.post("/reg".async ctx => {
ctx.body = ctx.request.body;
const finds = await User.find({ name: ctx.request.body.name })
if (finds.length > 0) {
ctx.body = { msg: "User already exists"}}else {
const newUser = new User({
name: ctx.request.body.name,
sex: ctx.request.body.sex,
data: ctx.request.body.data
})
await newUser.save().then(res= > {
ctx.body = newUser
}).catch(err= > {
console.log(err); })}})module.exports = router.routes()
Copy the code