“This is the 14th day of my participation in the August Text Challenge.

This series summarizes some knowledge of the front-end request back-end interface. Before reading the second article, I want you to read the first article:

  • Front-end request back-end interface summary – where data is sent

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

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

Interface 1. Returns common data. Returns information such as the request 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 from the front end. Try it: http://111.229.14.189/gk-api/util/test? id=123

  • The second interface returns a file stream. You can also try: http://111.229.14.189/gk-api/util/download? file=1.jpg

This article focuses on the tools that send data requests and how each tool sets data in the URL, in the Header, and in the Body.

XMLHttpRequest

XMLHttpRequest is one of the earliest apis supported by browsers for asynchronous programming. Put a document for reference ->MDN document

The process for sending data using XMLHttpRequest is as follows (all requests are annotated) :

<script>
    
    const TEST_URL = 'http://111.229.14.189/gk-api/util/test'
    const TOKEN = 'Beard facajjdfjdjfjajdfj238u3284'
    // Test data
    const TEST_DATA = {
        json: JSON.stringify({ name: 'Jack'.password: '123456' }),
        url: 'name=Anna&password=123456'
    }
    const CONTENT_TYPE = {
        json: 'application/json'.url: 'application/x-www-form-urlencoded'
    }
    // -------------------code ; (function () {

        1. Instantiate the XMLHttpRequest object
        const xhr = new XMLHttpRequest()

        // 2. Initialize a request xhrreq.open (method, URL, async);
        xhr.open('POST', TEST_URL)

        // 3. Set the request header
        xhr.setRequestHeader('Content-type', CONTENT_TYPE.url)
        xhr.setRequestHeader('token', TOKEN) // Customize the request header

        // 4. Send request
        xhr.send(TEST_DATA.url)

        // 5. Get the response
        xhr.onload = function () {
            if (xhr.readyState == 4) {
                console.log('All response headers', xhr.getAllResponseHeaders())
                console.log('Single response header', xhr.getResponseHeader('content-type'))
                console.log('Response body Type'.typeof xhr.response)
                console.log('Response body', xhr.response)
                document.write(xhr.response)
            }
        }
    })()
</script>

Copy the code

Look at the comments above for the whole process

  1. Instantiate the XHR objectconst xhr=new XMLHttpRequest()
  2. Initialize the request, call the open method, and set the request method, URL, and whether to synchronizexhr.open(method,url,async)
  3. Set the request header. Note that the Content-Type header needs to be set based on the type of the request body data
  4. Send the request.xhr.send(data)
  5. inonloadGet the response in the callback function, you can get the response headerxhr.getAllResponseHeaders()And the response bodyxhr.response()

Fetch API

The Featch API is a new browser resource retrieval API that returns promises instead of the XMLHttpRequest API.

As above, detailed introduction to put an MDN document

It’s also very simple to use

<script>
    const TEST_URL = 'http://111.229.14.189/gk-api/util/test'
    const TOKEN = 'Beard facajjdfjdjfjajdfj238u3284'
    // Test data
    const TEST_DATA = {
        json: JSON.stringify({ name: 'Jack'.password: '123456' }),
        url: 'name=Anna&password=123456'
    }
    const CONTENT_TYPE = {
        json: 'application/json'.url: 'application/x-www-form-urlencoded'
    }
    / / 1. Then write
    const getData = function () {
        fetch(TEST_URL, {
            method: 'POST'.headers: {
                token: TOKEN,
                'Content-type': CONTENT_TYPE.url
            },
            body: TEST_DATA.url
        })
            .then((res) = > {// Determine how the response data should be processed in a promise
                return res.json()
            })
            .then((res) = > {// Process the response data in the second Promise
                console.log('res', res)
            })
    }
    //2
    const getData1 = async() = > {const res = await (await fetch(TEST_URL)).json()
        console.log('getData1 -> res', res)
    }
    // -------------------code; (function () {
        getData()
        getData1()
    })()
</script>

Copy the code

Fetch (URL,{method,headers,body}) returns a Promise object regardless of whether the request is successful. Resolve So we need to dot then twice. Set of writing method, remember can be.

AXIOS

AXIOS is a request library that is wrapped based on XMLHttpRequest and is easy to use.

Put a Chinese document for your reference

AXIOS recommends the following:

axios.request({
    url: URL,
    method: 'post'.The get method can be omitted
    headers: {/ / the HTTP request header
        token: 'Beard iuflaoweinvhauh'
    },
    params: {// The get method requests parameters? page=1&pageSize=10
        page: 1.pageSize: 10
    },
    data: {/ / the HTTP request body
        name: 'Jack'}})Copy the code

Note: AXIOS automatically sets the Content-Type header based on your data format, which is nice.

In the next article, I will deal with interface responses, including the processing of ordinary JSON data, as well as the processing of streams (images, Excel and other files).