Uniapp: Request Error 400 occurred in the request

Development requirements: When our team used UniApp Springboot to develop wechat small program project, the front end sent request request to the back end, and the front end burst 400 errors.

400 Error: Invalid (Bad request); This error indicates that the request did not enter the backend service

Cause: The data submitted by the front-end or the Url of the request cannot be encapsulated or processed in the back-end parameters; The header in the uniapp request must be written correctly. If the end fails to get the data from the front end, an error of 400 will occur.

Note that the request header is set to ‘Content-Type’ : ‘Application/X-www-form-urlencoded’ and method is set to PSOT.

Uni. Request The header in the request should be written as:

header: {
        "Content-Type": "application/x-www-form-urlencoded"
    }
Copy the code

Here, header writing involves data data description

We convert it to String based on whether the data we finally send to the server is of type String. If the data passed in is not of type String, it will be converted to String.

The conversion rules are as follows:

  • forGETMethod that converts the data to a Query String. For example,{ name: 'name', age: 18 }The result of the transformation isname=name&age=18.
  • forPOSTMethods andheader['content-type']application/jsonThe data will be JSON serialized.
  • forPOSTMethods andheader['content-type']application/x-www-form-urlencodedIs converted to a Query String.

Case study:

uni.request({
    url: 'https://www.example.com/request'.// This is an example, not a real interface address.
    data: {
        text: 'uni.request'
    },
    header: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    // header: {}, set the header of the request to application/json by default
    success: (res) = > {
        console.log(res.data);
        this.text = 'request success'; }});Copy the code

This post commemorates me and bug:400’s 8H