II. Get / Post receiving parameters in Koa2 framework

Keywords: Javascript node.js Front-end Vue.js koa2

One is to realize cross domain access

1. If the API you want to develop is called by the front-end project (such as Vue), the first step must be to realize cross domain access. The implementation of cross domain access in Koa2 framework is slightly different from that in Express. You need to install Koa2 CORS middleware to realize cross domain access with the help of Koa2 CORS

npm install koa2-cors -save

After the installation is completed, it is imported into the app.js file and configured with relevant contents

const cors = require('koa2-cors');
      origin: function(ctx) { //Set allow requests from the specified domain name
           if (ctx.url === '/test') {
               return '*'; // Allow requests from all domain names
           return 'http://localhost:8080'; // Only allowed http://localhost:8080 Request for this domain name

          //return '*'; //  Allow requests from all domain names
      maxAge: 5, //Specify the validity period of this pre inspection request, in seconds.
      credentials: true, //Allow sending cookies
      allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //'set allowed HTTP request methods'
      allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //Set all header fields supported by the server
      exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //Set get other custom fields

The above is the basic configuration. Through the origin function, only the specified domain name is allowed to access the API. For more parameters and configurations, please refer to koa2-cors.

Second, customize an API interface

1. We create a test.js file in the routes folder, refer to the example given in the project, and write the following contents

const router = require('koa-router')()
router.prefix('/test')  //Define route name
//Define a default Get API
router.get('/', function (ctx, next) {
  ctx.body = 'This is test.js Default interface for!'
module.exports = router

2. Refer to the default example given by the framework and use the test.js routing file in app.js

const test= require('./routes/test')
app.use(test.routes(), test.allowedMethods())

The usage here is not different from that of the Express framework, which is not difficult to understand. However, it should be noted that the route name is in the test.js route file.
If called, you can access http://localhost:3000/test , if the above steps are correct, the following content will appear.

From the above simple example, the value of ctx.body is equivalent to res.send() in the Express framework, and CTX is called context. When we assign a value to ctx.body, the default API execution of the framework ends and the data is returned. So what happens when we don't assign a value to ctx.body? Let's get rid of the assignment code.

router.get('/', function (ctx, next) {
  // Note: ctx.body
  // ctx.body = 'this is the default interface of test.js!'

Access interface http://localhost:3000/test ,

Let's take a look at the log content given by the terminal console.

The terminal console directly gives 404, which means I don't need to say more.

III. accept Get parameter

1. Through the above examples, we have simply learned how to return some data. Next, we will add a GetAPI with parameters to see how to obtain the parameters passed by the Get request.

router.get('/getinfo', function (ctx, next) {
  ctx.body = 'this is a users/bar response'

Then visit http://localhost:3000/test/getinfo?id=1&name=shawn
The console output is as follows:

As you can see, ctx.query has converted the parameters of the Get request into an object and directly returned it to us. We can accept it directly and use it.

2. Take another look at the param value in the Get request. Modify the interface as follows:

router.get('/getinfo/:id/:name', function (ctx, next) {
  ctx.body = 'this is a users/bar response'

Try again http://localhost:3000/test/getinfo/1/shawn
Monitor the console output

We use ctx.params to accept the param parameters passed by the Get interface. Please pay attention to distinguish the definition methods of the two interfaces.

IV. accept Post parameters

1. For test simulation of local Post interface, I will use a test tool: BB-API To facilitate testing.
2. Write a Post request interface:

router.post('/add', function (ctx, next) {
  console.log(ctx.request.body); //Use ctx.request.body to receive the parameters passed by the post request
  ctx.body = ctx.request.body

The BB-AP operation is as follows, which can be accessed by Post http://localhost:3000/test/add Interface

We can see the following log contents on the terminal console:

Therefore, we know that to obtain the parameters passed by the Post interface, use ctx.request.body.


1. It should be noted that when we directly output the value of ctx, we cannot find the attribute value mentioned above.
The above is just a simple use of Post/Get to obtain parameter values in the Koa2 framework. For more detailed principles and usage, please refer to Koa2 official documents

Posted by e11even on Mon, 01 Nov 2021 21:13:42 -0700