npm i koa --save
// const Koa = require(' Koa '); const app = new Koa(); App.listen (3000, () => console.log(' Service starts on port 3000! '))Copy the code
npm i koa-router –save
NPM I koa- bodyParser –save // Get the POST parameter
NPM I koa-parameter –save // Check parameters
NPM I koa-json-error –save // Process error messages and return error messages to the client in JSON format
const Router = require('koa-router'); const parameter = require('koa-parameter'); const bodyparser = require('koa-bodyparser'); const error = require('koa-json-error'); const app = new Koa(); const router = new Router(); // const userRouter = new Router({prefix: '/users'}); // Route path parameters are taken by ctx.request.query. // get parameters (e.g.? Router. get('/:id', CTX => {console.log(ctx.request.query); console.log(ctx.request.params); }); Body must be provided by koA-bodyParser middleware. // Ctx.verifyParams is passed to match whether the corresponding parameter complies with the rule. If it does not comply with the rule, 422 parameter verification error is returned. router.post('/', ctx => { ctx.verifyParams({ name: { type: 'string', require: false }, password: { type: 'string', require: true } }) console.log(ctx.request.body); }); // Using router.allowedMethods(), you can use the options request in the request header ALLOW to know which methods are implemented. App.use (router.routes()).use(router.allowedMethods())); app.use(bodyparser()); app.use(parameter(app)); App. use(error({postformat: (err, {stack,... other }) => { return process.env.NODE_ENV === "production" ? other : { stack, ... other }; }})) app.listen(3000, () => console.log(' Service starts on port 3000! '))Copy the code
NPM I mongoose --save mongoDB
const mongoose = require('mongoose'); Mongoose. Connect (mongoDBUrl, {useNewUrlParser: true, useUnifiedTopology: True}, () => console.log(" Mongoodb connection successful!" )); Mongoose.connection. on("error", console.error. Bind (console, "connection error:")); // Create a Schema with character information const UserSchema = Mongoose.Schema({name: {type: String, required: true}, password: {type: String, required: true}}) const User = mongoose. Model ('User', UserSchema); // Add // delete // change // searchCopy the code