Home  >  Article  >  Web Front-end  >  How to get HTTP parameters in Egg.js

How to get HTTP parameters in Egg.js

php中世界最好的语言
php中世界最好的语言Original
2018-03-24 09:16:444646browse

This time I bring to you, what are the precautions, the following is a practical case, let's take a look.

This time I will show you how to obtain HTTP parameters in Egg.js, and what are the precautions for obtaining HTTP parameters in Egg.js. The following is a practical case, let's take a look.

In the Egg.js framework, since the Controller is basically the only place that interacts with the HTTP protocol in business development, the framework provides many convenient methods and properties to obtain users through the Context instance bound to the Controller. Parameters sent through HTTP requests. This article summarizes the method of obtaining the parameters of the http request:

1.query

In the URL? The following part is a Query String, which is often used for GET type requests. Pass parameters in. For example, in GET /search?name=egg&age=26, name=egg&age=26 is the parameter passed by the user. We can get the parsed parameter body through context.query (which is an object)

module.exports = app => {  class SearchController extends app.Controller {
    * search() {      const queryObj = this.ctx.query;      console.log(queryObj.age);      console.log(queryObj);      //打印结果:{ name: 'egg', age: '26' }
    }
  }  return SearchController;
};

When the key in the Query String is repeated, context.query only takes the value when the key appears for the first time, and then Any further occurrences will be ignored. GET /posts?category=egg&category=koa The value obtained through context.query is { category: 'egg' }.

1.1 queries

Sometimes our system is designed to allow users to pass the same key, such as GET /posts?category=egg&id=1&id=2&id=3. For such situations, the framework provides the context.queries object, which also parses the Query String, but it does not discard any duplicate data, but puts them all into an array:

// GET /posts?category=egg&id=1&id=2&id=3const Controller = require('egg').Controller;module.exports = class PostController extends Controller {
  * listPosts() {    console.log(this.ctx.queries);    //result:
    // {
    //   category: [ 'egg' ],
    //   id: [ '1', '2', '3' ],
    // }
  }
};

If all keys on context.queries have values, they must be of array type.

2. Router params

We know that parameters can also be declared on the Router, and these parameters can be obtained through context.params.

// app.get('/projects/:projectId/app/:appId', 'app.listApp');// GET /projects/1/app/2const Controller = require('egg').Controller;module.exports = class AppController extends Controller {
    * listApp() {    assert.equal(this.ctx.params.projectId, '1');    assert.equal(this.ctx.params.appId, '2');
  }
};

3. body

Although we can pass parameters through the URL, there are still many restrictions:

The browser will have restrictions on the length of the URL. If necessary If too many parameters are passed, it will not be passed.

The server often records the complete URL accessed in the log file. It is not safe to pass some sensitive data through the URL.

We know that there is a body part after the header, and we usually pass the parameters of methods such as POST, PUT and DELETE in this part. Generally, when there is a body in the request, the client (browser) will also send Content-Type to tell the server what format the body of this request is. The two most commonly used formats for data transfer in web development are JSON and Form.

The framework has built-in bodyParser Middleware to parse the request body of these two types of formats into object and mount it on context.request.body. In the HTTP protocol, it is not recommended to pass the body when accessing through the GET and HEAD methods, so we cannot obtain the content in the GET and HEAD methods according to this method.

// POST /api/posts HTTP/1.1// Host: localhost:3000// Content-Type: application/json; charset=UTF-8//// {"title": "controller", "content": "what is controller"}const Controller = require('egg').Controller;module.exports = class PostController extends Controller {
  * listPosts() {    assert.equal(this.ctx.request.body.title, 'controller');    assert.equal(this.ctx.request.body.content, 'what is controller');
  }
};

The framework sets some default parameters for bodyParser. After configuration, it has the following characteristics:

When the requested Content-Type is application/json, application/json-patch+json, application/ When using vnd.api+json and application/csp-report, the request body will be parsed according to the json format, and the maximum length of the body will be limited to 100kb.

When the Content-Type of the request is application/x-www-form-urlencoded, the request body will be parsed according to the form format, and the maximum length of the body will be limited to 100kb.

If the parsing is successful, body must be an Object (maybe an array).

Generally speaking, the configuration item we adjust most often is to change the maximum length allowed during parsing. You can override the default value of the framework in config/config.default.js

module.exports = {
  bodyParser: {
    jsonLimit: '1mb',
    formLimit: '1mb',
  },
};

If the user's If the request body exceeds the maximum parsing length we configured, an exception with a status code of 413 will be thrown. If the body requested by the user fails to be parsed (wrong JSON), an exception with a status code of 400 will be thrown. abnormal.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Mysqld_multi deployment stand-alone detailed explanation

How to query different databases with one SQL statement

JS gets the value in the first element in the select drop-down box

The above is the detailed content of How to get HTTP parameters in Egg.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn