In the last article, we discussed status code 304 and headers related to HTTP caching, Cache-control (RES), Expires (RES), etag(RES), if-none-match (REq), last-Modified (RES), if-Modified-since (REQ). As you can see from the last two articles, HTTP response and request packets are just too important to be separated from each other. Back-end developers have more control over HTTP than front-end developers. With the separation of the front and the back end, students pay more attention to the back end of various business logic, only responsible for the front-end interface. So the question is, sometimes you might ask, why debug this interface this way? Why pass parameters like this? Why do front-end validation do this? This article starts with these questions and discusses HTTP methods and Ajax encapsulation ideas (axios as an example). Of course, ajax encapsulates a lot of code on the web, so this article won’t repeat the old wheels, but aims to understand why it does so, and to sort out the connection with HTTP methods.

Before discussing HTTP methods, let’s review some of HTTP’s features ^-^. HTTP did not have the concept of persistent links prior to version 1.0. It was wasteful to establish a TCP three-way handshake with one request; So, HTTP1.1 has been added

Connection: keep-alive

Copy the code

This field is present in both the request header and response header. Currently, most browsers allow up to six persistent connections to the same domain name. Sometimes there are so many requests that the 6 connections are too busy to handle that front-end performance tuning is involved (The interview questions). How do we send requests? Ajax! (The common bidirectional one is WebscoktHTTP methods are used to make requests, essentially to tell the server the intent of the client, so these methods are as good as their name suggests.

The whole method is as follows:



Commonly used areGet (check).Post (add).Put (change).Delete (delete)Restful style; Get and Post are often asked what the difference is (The interview questions), there are many very detailed answers on Zhihu, I only make a simple comparison here.

  • getPass parameters using? k=v&k1&=v2In the request link directly after the parameter value of the form, sometimes usedencodeURIComponentThe function escapes the following character.
  • postThere are generally three kinds of parametersFormData (QS transfer parameter),Request PayloadAnd for uploading filesmultipart/form-data

    We encapsulate Ajax as the difference between parameter passing. One of these methods is a special oneoptionsThis method often appears inCORSBefore a cross-domain request. The purpose is to determine which request methods the resource server supports, but of course simple requests are not triggeredCORSpreview.

I don’t need to say much about Ajax, but interviews are often written with native Ajax. Let’s do this with XMLHttpRequest:

function callBack () {

console.log(this.responseText)

}



let xhr = new XMLHttpRequest()

xhr.onload = callBack

xhr.open(method, url, true)

xhr.send()

Copy the code

The fetch version

let myHeaders = new Headers()



let myInit = { method: 'GET',

headers: myHeaders,

mode: 'cors',

cache: 'default' }



fetch('flowers.jpg',myInit)

.then(function(response) {

return response.blob()

})

.then(function(myBlob) {

var objectURL = URL.createObjectURL(myBlob)

myImage.src = objectURL

})

Copy the code

Of course, this object and method have a lot of attributes and methods, we are not often with native request, processing is more laborious and certain compatibility problems, know that means the line, learn to have the power to check MDN research. Let’s use axios, the most popular Ajax library, as an example to encapsulate a powerful, customized Ajax, and see how HTTP methods are encapsulated. Take a “piece” of Axios, with a copy of the QS module:

import axios from 'axios'

import qs from 'qs'

// Generate an axios instance with a request method.

const service = axios.create({

BaseURL: process.env.mock_url,// Dev and build split with node global variables

timeout: 180000

})



/ * *

* Common request encapsulation

* @param method

* @param url

* @param data

* @param config

* @returns {Promise}

* /

const request = (method, url, data, config = {}) => {

const options = Object.assign({}, config, {

url,

method,

data

})

options.headers = options.headers || {}

Return new Promise((resolve, reject) => {// Use a Promise to put a shell on the result

Service.request (options) // The instance sends the request

.then(res => {

const data = res.data

const status = res.status

if (status === 200) {

resolve(data)

}

Resolve (data) // The processing here is not very rigorous

}).catch(res => {

reject(res)

})

})

}

// Expose external methods

export const ajax = {

get(url, config) {

return request('get', url, null, config)

},

delete(url, data, config) {

return request('delete', url, data, config)

},

head(url, config) {

return request('head', url, null, config)

},

post(url, data, config = {}) {

if (! config.headers) {

// Set the request header parameters

config.headers = {

'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'

}

}

return request('post', url, qs.stringify(data), config)

},

put(url, data, config = {}) {

// Set the request header parameters

config.headers = {

'Content-Type': 'application/json; charset=UTF-8'

}

return request('put', url, data, config)

},

patch(url, data, config) {

return request('path', url, qs.stringify(data), config)

},

setCommonHeader(key, value) {

service.defaults.headers.common[key] = value

}

}

Copy the code

Sometimes we need token authentication, or cookies, but it’s just adding something to the request header. Axios can operate through interceptors.

service.interceptors.request.use(config => {

// Do something before request is sent

if (store.getters.token) {

Config. Headers [' x-token '] = "// Make each request carry the Token -- [' x-token '] is a user-defined key. Change it according to the actual situation

}

return config

}, error => {

// Do something with request error

console.log(error) // for debug

Promise.reject(error)

})

Copy the code

Sometimes we log in too long and need to log in again, which is to judge the things in response and make a redirection.

service.interceptors.response.use(function(response) {

// Redirect according to conditions

if (response.headers.loginstate === 'expired') {

// router.push({ path: '/login' })

}

return response

}, function(error) {

return Promise.reject(error)

})

Copy the code

Package code refer to vue-admin project to be continued

Please leave me a comment on GitHub. Let’s learn and improve together.