Start by creating a koA folder
NPM init -y // Initializes the projectCopy the code
Install the required plug-ins
NPM install koa-router -s // Install koa-router NPM install mongodb // Install mongodb NPM install Mongoose NPM install koa-body // Install koa-bodyCopy the code

The first one is installed separately, you can also install it all at once:

npm i koa  koa-router mongodb mongoose koa-body -S
Copy the code

The installation is as follows:

First, start writing

Set up the app. Js

const Koa = require('koa'); const Router = require('koa-router'); const koaBody = require("koa-body"); // enter koa-body //koa, router, const app = new koa (); const router = new Router(); app.use(koaBody()); router.get('/',ctx =>{ ctx.body = 'hello world' }) app.use(router.routes()).use(router.allowedMethods()); App.listen (3000,()=>{console.log(" service started ")})Copy the code

Add it to package.json

"dev": "nodemon app.js"
Copy the code

NPM run dev:

Visit the page where the page is: if it looks like the following, your project is already started

The effect of creating a directory is as follows: (personal habit is to create the required files and folders in advance) not all user.js can be changed to your favorite name. But be careful when you introduce it

Connect to the remote free mongodb database

The stuff in the vue.config.js configuration string ahead of time is copied in the MongoDBCompass format that must be

inapp.jssTo add

const Koa = require("koa"); const Router = require("koa-router"); const koaBody = require("koa-body"); + const mongoose = require("mongoose"); + const { connectionStr } = require("./vue.config.js"); Connect (connectionStr, (err) => {+ if (err) console.log("mongonDB connection failed "); + console.log("mongonDB connection succeeded "); +}); //koa instantiate const app = new koa (); const router = new Router(); Routing add prefix/API / / total, total address into the router. http://localhost:3000/api prefix ("/API "); router.get("/", async (ctx) => { ctx.body = "hello World"; }); app.use(koaBody()); app.use(router.routes()).use(router.allowedMethods()); App.listen (3000, () => {console.log(" service started "); });Copy the code

You will see:

That would have been an interception(I'll just break it down)

One, in theroutes/user.jsWrite in the folder

const Router = require('koa-router'); const router = new Router(); // Const {find, findById, create, update, delete: del,} = require('.. /controllers/user'); router.get('/', find); Router. Post ('/', create); // Add router.get('/:id', findById); Update router. Patch ('/:id', update router); // Modify router.delete('/:id', del); Module. exports = router;Copy the code

Second, incontrollers/user.jsWrite in the folder

const User = require(".. /models/users.js"); class UsersCtl { async find(ctx) { ctx.body = await User.find(); } async findById(ctx) { const user = await User.findById(ctx.params.id); if (! User) {ctx.throw(404, "user does not exist "); } ctx.body = user; } async create(ctx) { const user = await new User(ctx.request.body).save(); ctx.body = user; } async update(ctx) { const user = await User.findByIdAndUpdate(ctx.params.id, ctx.request.body); const users = await User.findById(ctx.params.id); if (! Users) {ctx.throw(404, "user does not exist "); } ctx.body = users; } async delete(ctx) { const user = await User.findByIdAndRemove(ctx.params.id); if (! User) {ctx.throw(404, "user does not exist "); } ctx.status = 204; } } module.exports = new UsersCtl();Copy the code

Third, inmodels/user.jsWrite in the folder

const mongoose = require("mongoose"); const { Schema, model } = mongoose; // Write some required fields // Required: true is mandatory // Number default: 0 default: 0 // string default: Const userSchema = new Schema({name: {type: String, required: true}, age: {type: Number, default: 0 }, state:{ type: String, default: "" } }); module.exports = model("User", userSchema, "users");Copy the code

Fourth, finally, don’t forget the overall situationapp.jsIt introduces the following:

const Koa = require("koa"); const Router = require("koa-router"); const koaBody = require("koa-body"); const mongoose = require("mongoose"); + const user = require("./routes/user.js"); const { connectionStr } = require("./vue.config.js"); Mongoose. Connect (connectionStr, (err) => {if (err) console.log("mongonDB connection failed "); Console. log("mongonDB connection succeeded "); }); //koa instantiate const app = new koa (); const router = new Router(); Routing add prefix/API / / total, total address into the router. http://localhost:3000/api prefix ("/API "); router.get("/", async (ctx) => { ctx.body = "hello World"; }); app.use(koaBody()); / / zi lu by prefixing/users, and finally into http://localhost:3000/api/users/user + access address the router. Use ("/users, "the user. The routes ()); app.use(router.routes()).use(router.allowedMethods()); App.listen (3000, () => {console.log(" service started "); });Copy the code

Five, the last folder left unsaid, that isdataFolder is the default empty array for data[]Otherwise, an error will be reported.

I suggest you test the interface on Postman to see if it works properly and change it if you have any errors. Different methods of request return different results //

My add effect:

Find: he is a direct child ah behind the splice id

Modification:

I’m not going to show you the rest

Thanks for watching !!!!