“This is my 18th day of the November Gwen Challenge.The final text challenge in 2021” |
---|
I will continue to study the KOA framework today (~ ▽ ~).”
This article introduces some of the plug-ins commonly used for KOA:
@koa/cors
Cross domain processingkoa-body
Protocol processing
Use koa-body and @KOA/CORS
koa-body
Process data from requests@koa/cors
Handle some cross-domain requests
NPM install -s koa-body@koa /cors
Note: You need to first use koa-body to process the data in the incoming request, and then use @koA/Cors to process some cross-domain requests
Get the post value in Koa
var Koa = require('koa');
var Router = require('koa-router');
var cors = require('@koa/cors');
var koabody = require('koa-body');
var app = new Koa();
var router = new Router();
router.post('/post'.async (ctx, next) => {
let {body}=ctx.request;// Get the value given by the front end
ctx.body={// Return the contents of the body to the front end. body } });//app.use pay attention to the order
app.use(koaBody())// Process the data from the request
app.use(cors())// Handle some cross-domain requests
app.use(router.routes())
.use(router.allowedMethods());
app.listen(3000);
Copy the code
Get and get get values in Koa
-
Key/value pair concatenation and parameter transmission. The received parameters are mainly obtained through ctx.qruery. It should be noted that the same result can be obtained in CTX and CTX.
-
Parameters are transmitted through dynamic routes. The received parameters are obtained through ctx.params.
The following is an example of key-value pair concatenation:
var Koa = require('koa');
var router = require('koa-router') ();var app = new Koa();
// http://localhost:3000/details? id=1&name=jiangyx
router.get('/details'.async(ctx)=>{
// Read the Get pass from CTX
console.log(ctx.url);// /details? id=1&name=jiangyx
console.log(ctx.query); // {id: '1', name: 'jiangyx'
console.log(ctx.querystring) // id=1&name=jiangyx //
// Get the Get from the request in CTX
console.log(ctx.request.url); // /details? id=1&name=jiangyx
console.log(ctx.request.query); // { id: '1', name: 'jiangyx' }
console.log(ctx.request.querystring); // id=1&name=jiangyx
});
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
Copy the code
The following is an example of dynamic route parameter transmission:
var Koa = require('koa');
var router = require('koa-router') ();var app = new Koa();
// http://localhost:3000/details/1/jiangyx
router.get('/details/:id/:name'.async (ctx) => {
// Get the value of the dynamic route
console.log(ctx.params); // { id: '1' ,name:'jiangyx'}
});
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
Copy the code