• koa2
  • Koa-bodyparser – Middleware that receives POST request parameter conversions
  • Koa-router — Request route
  • Koa-static – Static resource access middleware

1. Initialize NPM init

2. NPM install KOA

3 Install related middleware

package.js

"Name" : "jc", "version" : "1.0.0", "description" : ""," main ":" index. Js ", "scripts" : {" test ", "echo \" Error: No test specified \ "& & exit 1}", "author" : ""," license ":" ISC ", "dependencies" : {" koa ":" tokens ^ 2.13.1 ", "koa - bodyparser" : "^ 4.3.0 koa", "- the router" : "^ 10.0.0", "koa - static" : "^ 5.0.0",}}Copy the code

4 index.js

// router middleware const router = require('koa-router'); Const BodyParser = require('koa-bodyparser'); // node native file path const path = require('path'); // static middleware const static = require('koa-static') const app = new koa (); // Static path const staticPath = "./static" // middleware router const router = new Router() // Middleware gets post request parameter object const bodyParser = new BodyParser(); app.use(bodyparser); app.use(static(path.join(__dirname,staticPath))) // app.use(async (ctx)=>{ // console.log(ctx) // If (CTX) url = = = "/ what" && CTX) method = = = "GET") {/ / CTX. Body = 'original request not to use the router middleware / /}}) / / / GET request Router. Get ('/',async(CTX)=>{ctx.body= '<form action="/getForm" method="get"> <input type="submit" value=" post request "/ > Get ('/getForm',async(CTX)=>{// get request parameter object ctx.body= '<form action="/" method="post"> <p>First name: <input type="text" name="fname" /></p> <p>Last name: <input type="text" name="lname" /></p> <input type=" value=" submit" /></ form> '}) // Post request Router.post ('/',async(CTX)=>{// ctx.request.body Gets the POST request parameter object (this time using bodyParser middleware) ctx.body=ctx.request.body}) router.get('/setCookies',async(ctx)=>{ // * ctx.cookies.set(name, value, [options]) // * Set the value of cookie name with options // * maxAge a number representing the number of milliseconds obtained from date.now () // * signed cookie signature value // * path Cookie path, default is '/' // * domain cookie domain name // * secure cookie // * httpOnly server accessible cookie, Default is true // * overwrite a Boolean value Indicates whether to override previously Set cookies with the same name (default false) // * If true, whether all cookies (regardless of path or field) with the same name in the same request are filtered from the set-cookie header when this cookie is Set. ctx.cookies.set( "cookies","cookies",{ // maxAge:10000, expires:new Date("2021-06-24"), overwrite:false, Body ="setCookies"}) router.get('/getCookies',async(CTX)=>{ Body = ctx.cookies. Get ("cookies")}) // app.use(async CTX => { // console.log(ctx.url) // ctx.body = 'Hello World'; / /}); app.use(router.routes()); app.use(router.allowedMethods()); App.listen (3000,()=>{console.log(" Server started... )});Copy the code

5 Node index.js starts