[Express.js] Processing request data

process request data

This section will specifically introduce some methods and techniques for the express backend to process the data carried by the request source

dynamic path

Many times we need to deal with some similar businesses that have different operations or different objects. We can monitor a basic path, use one or several paths as variables, and perform different business operations in the interface according to different path variables. , which is a dynamic interface design strategy with a distinct REST style

practice

Since post can also pass parameters in url, all examples in this section use post request

first interface

This interface uses /request/data/ as the base route, and the subsequent kind changes, and branching is performed within the interface according to the value of the kind. I specified three values ​​of kind: PathVarible, RequestParam and body.
All path parameters can req.paramsbe obtained by (probably a json object). I want to specify the value of kind, req.params.kind, and static path variables The value is equal to its name.

//忽略了express项目的创建和基本配置
class Item {
    
    
    constructor(name, value) {
    
    
      this.name = name;
      this.value = value;
    }
}
//启用json解析请求体
app.use(express.json({
    
    type: 'application/json'}));
app.post('/request/data/:kind', function (req, res) {
    
    
    let result = [];
    if (req.params.kind == 'PathVarible') {
    
    
        result.push(new Item("lesson","路径变量"));
        result.push(new Item("info","在express中叫做params,路径上每个被双单斜杠'/'隔开的一个个词语就是路径参数,当你需要在同一个接口内动态响应不同的情景时,可以让某一处或多出的路径参数前面加上一个冒号,长得比较像vue中的动态绑定,动态路径在REST风格上被广泛运行,比如操作某个用户: 'user/:id => 'user/1"))
    } else if (req.params.kind == 'RequestParam') {
    
    
        result.push(new Item("lesson","请求参数"));
        result.push(new Item("info","在express中叫做query,和路径变量相比,前者更像是前端主动携带参数去访问特定的资源,而后者更像是后端要求必须携带的数据,前端被迫携带,反应在路径上形式一般是: '/stu?class=2&sid=1&name='evanp',在基本路径之后添上一个问号,然后在后面加上请求的参数,不同参数之间用'&'符号隔开"))
    } else if (req.params.kind == 'body') {
    
    
        result.push(new Item("lesson","请求体"));
        result.push(new Item("info","路径变量和请求参数的数据都是透明的,这非常不注重隐私,因此更多时候前端应该将携带的数据放在请求体内进行传输。请求体的形式有很多,最常用的是表单和JSON,请在路径后新增一个路径变量,form-urlencode, multi-form-data或json导向不同的接口进行查看"));
    } else {
    
    
        result.push(new Item("error","这个参数不认识"));
    }
    res.send(result);
});

interface test

Please use the interface debugging tool, bring the path query parameter (query), and then modify different kinds to different values, go to POST to access localhost:8080/request/data/kind, and check their return results. Note that do not add before kind The colon, the colon is used to let express know that this path is variable

second interface

When a certain branch of the first interface can still have subsequent operations, you can open another interface and use it as the base route, and add a dynamic path later. For example, if I want the body to be redirected to different branches, then Open a /request/data/body/:kind interface

app.post('/request/data/body/:kind', function (req, res) {
    
    
    let result = [];
    if (req.params.kind == 'json') {
    
    
        result.push(new Item("lesson","json请求体"));
        result.push(new Item("body",req.body));
        result.push(new Item("info","express想解析json形式的body,必须先开启express.json: 'app.use(express.json)',之后就可以用req.body来接收请求体了"));
        result.push(new Item("trick","进阶技巧,读取请求体时可以用match模式匹配成自己想要的格式或命名,常用于实体注入及转化等"));
    } else if (req.params.kind == 'form-urlencode') {
    
    
        result.push(new Item("lesson","form-urlencode请求体"));
        result.push(new Item("body",req.body));
    } else if (req.params.kind == 'multi-form-data') {
    
    
        result.push(new Item("lesson","multi-form-data请求体"));
        result.push(new Item("body",req.body));
    } else {
    
    
        result.push(new Item("error","这个参数不认识"));
    }
    res.send(result);
});

interface test

Please use the interface debugging tool, bring the JSON request body, go to POST to access localhost:8080/request/data/body/kind, modify different kinds, and see their return results

Get path parameters

Base

The path parameter refers to the id and name in the url of '/url?id=1&name=evanp', which are in plain text and have no privacy, and
can be req.queryobtained

app.post('/request/data/query/info',checkQuery, (req, res)=> {
    
    
    res.send(req.query);
});

Try to use the interface debugging tool to access localhost:8080/request/data/query/info, and carry any query parameters

Query preflight

In the actual scenario, each interface will specify the query parameters of which names are required. Assuming that the above interface requires id and name, it is necessary to ensure that the front end does pass these two query parameters to the interface. Express does not enter parameters like springboot The inspection can be stipulated at any time, and we must personally inspect the passed query. The operation of this part of the inspection is not recommended to be included in the main callback function of our interface, but should be used as a middleware to complete the inspection before the callback:

Define a function to check the query to determine whether there is an id and name, if yes, continue, if not, return an error message directly

function checkQuery(req,res,next) {
    
    
    if (req.query.id == undefined ||
        req.query.id == null ||
        req.query.name == undefined ||
        req.query.name == null){
    
    
        res.send({
    
    "msg": "query不齐全"});
    } else {
    
    
        next();
    }
}

Introduce the middleware function when entering the interface parameters

app.post('/request/data/query/info',checkQuery, (req, res)=> {
    
    
    res.send(req.query);
});

Try to use the interface debugging tool to access localhost:8080/request/data/query/info, and compare the returned results without id, name and with id, name

get request body

JSON request body

Introduce the following code once

app.use(express.json({
    
    type: 'application/json'}));

Form (x-www-form-urlencoded)

x-www-form-urlencode encodes form data into a string in URL form

Introduce the following code once

app.use(express.urlencoded({
    
    extended: true}));

Regarding the extended parameter, it refers to parsing the form data (in the form of a URL encoded string) into a simple object or a deeply nested object.
What does it mean? For example, when extended=false, the data is passed in the form like this: Among
them, there are two identical key names: For example,
after passing two x, the field will refer to an array collection of all their values ​​after parsing: x=1&x=2-> {'x': ['1','2']}, even if both x are 1, it is also an array: {'x': ['1','1']}
among them, some key names are passed in the object attribute format, such as user[uname] in the figure below:
Form pass nested object
if we access the body/form-urlencode before the api debugging tool The interface transmits the data of the two cases in the form of the form at the same time, and the return result will be as follows:

[
    {
    
    
        "name": "lesson",
        "value": "form-urlencode请求体"
    },
    {
    
    
        "name": "body",
        "value": {
    
    
            "user[uname]": "evanp",
            "user[passwd]": "iloveu",
            "x": [
                "1",
                "2"
            ]
        }
    }
]

When extended=true, it is:

[
    {
    
    
        "name": "lesson",
        "value": "form-urlencode请求体"
    },
    {
    
    
        "name": "body",
        "value": {
    
    
            "user": {
    
    
                "uname": "evanp",
                "passwd": "iloveu"
            },
            "x": [
                "1",
                "2"
            ]
        }
    }
]

Through comparison, we can find extended=falsethat express is relatively naive and does not intelligently parse the user into an object; I think the usefulness of intelligent parsing is probably to save us manually injecting attributes into the object one by one.

form validation

We have verification requirements for request parameters. Similarly, form verification will naturally exist, and may even be more demanding, because security issues need to be considered. If there are no special requirements, you can write a
middleware function to check the form yourself. If For more advanced requirements, you can use threaded js libraries, such as express-validator , etc.

Form (multi-form-data)

This is a form that can pass strings and files at the same time. In fact, it is an upgraded version of the basic form.

Need to install multer dependency in advance: npm install multer
import dependency middleware:

const multer = require('multer');
const uploads = multer();

Introduce the middleware uploads in the interface that needs to receive files:

app.post('/request/data/body/:kind', uploads.any(), function (req, res) 

req.filesAll files can be obtained by passing in the main body callback function :

console.log(req.files); //写在multi-form-data分支下,方便区分

test interface

Use the composite form of the api debugging tool to carry the file and send the request to the body/multi-form-data interface, check our console:

[
  {
    
    
    fieldname: 'file',
    originalname: 'C.jpeg',
    encoding: '7bit',
    mimetype: 'image/jpeg',
    buffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 48 00 48 00 00 ff db 00 43 00 0a 07 08 09 08 06 0a 09 08 09 0c 0b 0a 0c 0f 1a 11 0f 0e 0e 0f 1f 16 18 13 ... 9752 more bytes>,
    size: 9802
  }
]

Yes, I just uploaded a picture called C.jpeg to the server

Next Section - Response

Guess you like

Origin blog.csdn.net/m0_51810668/article/details/131277958
Recommended