Network request mode

Traditional Ajax XMLHttprequest (XHR) based Configuration and debugging mess
jQuery-Ajax It’s not necessary to introduce jquery in order to introduce Ajax
Vue-resource Vue-resource is much smaller than JQ It has not been updated since Vue2.0
Jsonp Resolve cross-domain problems
axios

Jsonp: The project is deployed on the Domain1.com server and cannot directly access the data on the domain2.com server. At this point, the SRC of the script tag is used to request the data, and the data is executed as a JS function, and we need JSON in the process of execution

The core of encapsulating Jsonp is listening for the name of the Jsonp callback on the window

Why Axios?

  • Sends XMLHttpRequests requests in the browser
  • Send HTTP requests in Node.js
  • Supporting Promise API
  • Intercept requests and responses
  • Transform request and response data

Axios is basically used

The installation

npm i -s axios

The introduction of

import axios from 'axios'
Copy the code

test

axios({
	url: 'http://123.207.32.32:8000/home/multidata'
}).then(res= > {
	console.log(res)
})
Copy the code

Why use.then()?

The return value of the AXIos function is a Promise object

Why not write request mode?

The axios default request is GET

Test the web site httpbin.org/

The test interface http://123.207.32.32:8000/home/multidata

The way axios requests

get

You can put it in parameters

You can also use axios.get() directly

axios({
	url: 'http://123.207.32.32:8000/home/multidata'.method: 'get'
}).then(res= > {
	console.log(res)
})
Copy the code
axios.get()
Copy the code

With the cords

axios({
	url: 'http://123.207.32.32:8000/home/multidata? type=sell&page=3',
}).then(res= > {
	console.log(res)
})
Copy the code

Is equivalent to

axios({
	url: 'http://123.207.32.32:8000/home/multidata'.// Specifically for GET request parameter concatenation
    params: {
        type: sell
        page: 3
    }
}).then(res= > {
	console.log(res)
})
Copy the code

post

In the same way

A POST request has a request body

data: {id: 2}

axios.all()

  • The result is an array
  • Axios.spread expands the array [res1,res2] to res1,res2

What about sending two requests at the same time?

axios.all([axios({
    url: 'http://123.207.32.32:8000/home/multidata'
}),axios(
    url: 'http://123.207.32.32:8000/home/multidata'.params: {
    	type: 'sell'.page: 3
    }
)]).then(res= > {consloe.log(res)})
Copy the code

Return result expansion

axios.all([axios({
    url: 'http://123.207.32.32:8000/home/multidata'
}),axios(
    url: 'http://123.207.32.32:8000/home/multidata'.params: {
    	type: 'sell'.page: 3
    }
)]).then(axios.spread((res1, res2) = > {
    console.log(res1)
    console.log(res2)
}))
Copy the code

Global configuration

When the parameters are fixed, the global configuration can be extracted

axios.defaults.baseURL = 'http://123.207.32.32:8000'
axios.defaults.headers.post[Content-Type] = 'application/x-www-form-urlencoded'
Copy the code

Axios instance

const instance1 = axios.create({
    baseURL: 'http://123.207.32.32:8000'
})
instance1({
    url: '/home/multidata',
}).then(res= > {
	console.log(res)
})
Copy the code

Axios encapsulation

Create a network folder in the project root directory and create a request.js file in this folder

// request.js
import axios from 'axios'

export function request (config, success, failure) {
  // 1. Create an axios instance
  const instance = axios.create({
    baseURL: 'http://123.207.32.32:8000'.timeout: 5000
  })
  // Send a real network request
  instance(config)
    .then(res= > {
      success(res)
    }).catch(err= > {
      failure(err)
    })
}

Copy the code

Where you need to make a network request

// Introduce the request module
import { request } from './network/request'
request({
  url: '/home/multidata'
}, res= > {
  console.log(res)
}, err= > {
  console.log(err)
})
Copy the code

Promise way

// request.js
import axios from 'axios'

export function request (config) {
  return new Promise((resolve, reject) = > {
      // 1. Create an axios instance
      const instance = axios.create({
        baseURL: 'http://123.207.32.32:8000'.timeout: 5000
      })
      // Send a real network request
      instance(config)
        .then(res= > {
          resolve(res)
        }).catch(err= > {
          reject(err)
        })
      })
}
Copy the code

Where you need to make a network request

// Introduce the request module
import { request } from './network/request'
request({
  url: '/home/multidata'
}).then(res= > {
    console.log(res)
}).catch(err= > {
    console.log(err)
})
Copy the code

Why does axios.create create instances with a. Then method?

This method creates an instance of the Promise object

so

Final plan

// request.js
import axios from 'axios'

export function request (config) {
  // 1. Create an axios instance
  const instance = axios.create({
    baseURL: 'http://123.207.32.32:8000'.timeout: 5000
  })
  // Send a real network request
  return instance(config)
}
Copy the code

Where you need to make a network request

// Introduce the request module
import { request } from './network/request'
request({
  url: '/home/multidata'
}).then(res= > {
    console.log(res)
}).catch(err= > {
    console.log(err)
})
Copy the code

experience

Components should not be too dependent on third-party modules

If 50 components are introduced to AXIOS, it’s dangerous to change 50 components in case AxiOS doesn’t maintain them one day

But you have to use it. What do you do?

Packaged into separate modules, components can be imported as desired

When AXIos is not maintained one day, there is no need to change all the components one by one

Just change that part of the packaged code (to another third-party module)

Axios interceptor

It is used for processing each time a request is sent or a response is received

Request to intercept

Request interception must return config, otherwise the request will not be sent……

What does request interception typically do?

  • For example, some information in config does not meet the requirements of the server (header, of course header can also be set in public parameters).
  • For example, every time a network request is sent, you want to display an animation or icon of the request in the interface
  • Some network requests (login token) must carry some special information, or perform related operations (such as switching to the login interface without login).
import axios from 'axios'

export function request (config) {
  // 1. Create an axios instance
  const instance = axios.create({
    baseURL: 'http://123.207.32.32:8000'.timeout: 5000
  })
  // 2. Request blocking
  instance.interceptors.request.use(config= > {
    console.log(config)
    return config
  }, err= > {
    console.log(err)
  })
  // 3. Send a real network request
  return instance(config)
}
Copy the code

The response to intercept

Response interception must return an RES, otherwise the response result will not be retrieved…

But just return res.data, whose information is not needed

import axios from 'axios'

export function request (config) {
  // 1. Create an axios instance
  const instance = axios.create({
    baseURL: 'http://123.207.32.32:8000'.timeout: 5000
  })
  // 2. Response interception
  instance.interceptors.response.use(res= > {
    console.log(config)
    return res
  }, err= > {
    console.log(err)
  })
  // 3. Send a real network request
  return instance(config)
}
Copy the code