Create a koA folder
npm init -y    // Initialize the project
Copy the code
Install the required plug-ins
npm install koa -S   / / installation of koa
npm install koa-router -S   / / install koa - the router
npm install mongodb   / / install mongo
npm install mongoose   / / install the mongoose
npm install koa-body   / / install koa - body
Copy the code

You can also install them all at once:

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

After installation:

First, start writing

Set up the app. Js

const Koa = require('koa');
const Router = require('koa-router');
const koaBody = require("koa-body");  / / into the koa - body
// Instantiate koA and 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());
// Create port 3000, not necessarily 3000
app.listen(3000.() = >{
console.log("Service started")})Copy the code

In package.json

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

Running NPM run dev has the following effect:

Visit the page where the page is:

As shown in the following figure, your project is already started

Start to create the directory effect is as follows: (personal habit to set up the required files and folders in advance) not all to user. Js can be replaced with their own favorite name. But you have to be careful when you introduce it

2. Connect to the remote free mongodb database

Everything in the vue.config.js configuration string in advance is copied from the MongoDBCompass format

app.jssAdd to

const Koa = require("koa");
const Router = require("koa-router");
const koaBody = require("koa-body");
+ const mongoose = require("mongoose");
+ const { connectionStr } = require("./vue.config.js");
+ mongoose.connect(connectionStr, (err) = >{+if (err) console.log("MongonDB connection failed");
+   console.log("MongonDB connection successful"); +});/ / koa instantiation
const app = new Koa();
const router = new Router();
/ / total add prefix/API routing, total address to http://localhost:3000/api
router.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("The service is up.");
});
Copy the code

You will see:

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

One, in theroutes/user.jsIn the folder

const Router = require('koa-router');
const router = new Router();
// From controllers/user
const { find, findById, create,
update, delete: del, } = require('.. /controllers/user');
router.get('/', find); According to the total / /
router.post('/', create); / / add
router.get('/:id', findById);/ / to find
router.patch('/:id', update);  / / modify
router.delete('/:id', del); / / delete
module.exports = router;
Copy the code

Second, incontrollers/user.jsIn 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.jsIn the folder

const mongoose = require("mongoose");
const { Schema, model } = mongoose;
// Write the required fields in it
// Required: True is mandatory
// If it is a number, default: 0
// If it is a string default: "" is null by 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 is introduced as follows:

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 successful");
});
/ / koa instantiation
const app = new Koa();
const router = new Router();
/ / total add prefix/API routing, total address to http://localhost:3000/api
router.prefix("/api");

router.get("/".async (ctx) => {
  ctx.body = "hello World";
});
app.use(koaBody());

/ / zi lu by prefixing/users, and finally access address to http://localhost:3000/api/users/user
+ router.use("/users", user.routes());
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000.() = > {
  console.log("The service is up.");
});

Copy the code

Five, there is still one last folder not said, that isdataFolder is the default empty array where you put your data[]Otherwise, an error will be reported.

I suggest you test the interface on Postman, see if it works, and make changes if anything goes wrong. Different methods of requesting will return different results //

My add effect:

Search: he is directly son ah after the spliced ID

Modification:

I won’t show you the rest

Thanks for watching !!!!