How to get HTTP parameters in Egg.js
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

HTTP Status Code 200: Explore the Meaning and Purpose of Successful Responses HTTP status codes are numeric codes used to indicate the status of a server's response. Among them, status code 200 indicates that the request has been successfully processed by the server. This article will explore the specific meaning and use of HTTP status code 200. First, let us understand the classification of HTTP status codes. Status codes are divided into five categories, namely 1xx, 2xx, 3xx, 4xx and 5xx. Among them, 2xx indicates a successful response. And 200 is the most common status code in 2xx

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to implement HTTP streaming in C++? Create an SSL stream socket using Boost.Asio and the asiohttps client library. Connect to the server and send an HTTP request. Receive HTTP response headers and print them. Receives the HTTP response body and prints it.

The HTTP request times out, and the server often returns the 504GatewayTimeout status code. This status code indicates that when the server executes a request, it still fails to obtain the resources required for the request or complete the processing of the request after a period of time. It is a status code of the 5xx series, which indicates that the server has encountered a temporary problem or overload, resulting in the inability to correctly handle the client's request. In the HTTP protocol, various status codes have specific meanings and uses, and the 504 status code is used to indicate request timeout issues. in customer

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Solution: 1. Retry: You can wait for a period of time and try again, or refresh the page; 2. Check the server load: Check the server's CPU, memory and disk usage. If the capacity limit is exceeded, you can try to optimize the server configuration or increase the capacity. Server resources; 3. Check server maintenance and upgrades: You can only wait until the server returns to normal; 4. Check network connection: Make sure the network connection is stable, check whether the network device, firewall or proxy settings are correct; 5. Ensure cache or CDN configuration Correct; 6. Contact the server administrator, etc.
