“This is the 13th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”

This series mainly summarizes some knowledge of the front-end request back-end interface. Hopefully, after you read this, you’ll be comfortable with the backend interface.

For this series of articles, I wrote two test interfaces using Nodejs

/ / deploy IP:
http:/ / 111.229.14.189 / gk - API

// Interface 1. Return normal data. Return the header and request body sent by the front end
/util/test

// Interface 2. Return the file stream/util/download? file=fileNameCopy the code

The first interface returns some data sent by the front end. Try it out: http://111.229.14.189/gk-api/util/test? id=123

The second interface will return a file stream, or try http://111.229.14.189/gk-api/util/download? file=1.jpg

Where is the data sent and what format is it sent in

In general, there are three places you can put data

  • URL
  • Http Header
  • Http Body

The data is sent in a URL

Data is sent in a URL, and it takes two forms:

// Mode 1 uses template string concatenation parameters when sending requests
/user/:id

2 / / way/user? id=xxxCopy the code

Both forms of data format are URL-encoded, known as Application/X-wwW-form-Urlencoded

A recommended browser plug-in, FeHelper, can perform various forms of encoding conversion of data

The data is sent in headers

The data placed in the header is usually a custom request header, such as the token, UID and other fields

token:Beard xxxxjdjfj
uid:1
Copy the code

One thing to note here is that the data you put in the header must not appear in Chinese. If it appears in Chinese, an error will be reported

If you need to transfer Chinese, the distributor needs to use URLEncoder. Encode (” I am Chinese “, “UTF-8″) and the receiver needs to use URldecoder.decode (” string to be parsed “, “UTF-8”)

Send data in body (emphasis)

The format of the data sent in the body is determined by the content-type field in the HTTP request header.

There are many content-types. The following three types are used, each of which corresponds to a data format (the form of data organization)

//application/json  
{"name":"Jack"."pass":"* * * * *"}
//application/x-www-form-urlencoded
name=Jack&pass=*****
//multipart/form-data; boundary=----WebKitFormBoundary2mQN2wSPoRh4Wt1L
let formdata=new FormData()

Copy the code

To view the Content-type header in the browser:

Note: You must use multipart/form-data to upload files. The other interfaces will depend on the backend regulations. The first two can be converted to each other:

Application/json into application/x – WWW – form – urlencoded

// {"name":"Jack","pass":"*****"} -> name=Jack&pass=*****
// Iterate over the object to generate a string
/** * Object to THE URL parameter *@param {*} obj* /
export function getParams(obj) {
    return Object.keys(obj)
        .map(function(k) {
            return encodeURIComponent(k) + '=' + encodeURIComponent(obj[k])
        })
        .join('&')}Copy the code

X – WWW – form – urlencoded into json

//name=Jack&pass=***** -> {"name":"Jack","pass":"*****"}
function getObjByUrl(str){
  return   Object.fromEntries(new URLSearchParams(str));
}
//getObjByUrl('a=b&name=xxx%20djdj')


Copy the code

To simplify code when uploading files, objects can also be converted to FormData as follows:

/ * * * object into formdata {file: a file, id: XXX, name: XXX} - > formdata {} *@param {Object} object* /

 export function getFormData(object) {
    const formData = new FormData()
    Object.keys(object).forEach(key= > {
        const value = object[key]
        if (Array.isArray(value)) {
            value.forEach((subValue, i) = >
                formData.append(key + ` [${i}] `, subValue)
            )
        } else {
            formData.append(key, object[key])
        }
    })
    return formData
}
Copy the code

The next said.

The tools on the front end that send data requests, the native XMLHTTPRequest Fetch and the encapsulated framework axios, and how does each tool store data in the URL, the Header, and the Body and send it