Simple axios request package

▼Foreword:

The difference between Params and Data:
GETThe requested parameters are all URLon the server, the data in the http body will not be read, so what we pass is the request parameters in Params.

If you want the server to read the data in the http body, you need to use the POSTrequest, and the parameters of the POST request are stored in the body.

The summary usage method is as follows:
get方法用params,post方法用data。

PromiseTwo parameters of asynchronous request: resolvesuccessful callback function; rejectfailed callback function

▼Step by step reference
get request

let get = function (url, data) {
    
    
  return new Promise((resolve, reject) => {
    
    
    axios.get(url, {
    
    
      params: data
    }).then((res) => {
    
    
      //  请求成功返回后台数据
      resolve(res.data)
    }).catch((error) => {
    
    
      reject(error)
    })
  })
}

post request

let post = function (url, data) {
    
    
  return new Promise((resolve, reject) => {
    
    
    // qs.stringify()将对象 序列化成URL的形式
    axios.post(url, qs.stringify(data)).then((res) => {
    
    
    //  请求成功返回后台数据
      resolve(res.data)
    }).catch((error) => {
    
    
      reject(error)
    })
  })
}

▼Step by step reference
Requests that can be sent by post get requests

let request = function (url, method = 'GET', data = {
    
    }) {
    
    
  return new Promise((resolve, reject) => {
    
    
    axios({
    
    
      url: url,
      method: method,
      // post
      data: qs.stringify(data),
      // get
      params: data
    }).then((res) => {
    
    
      // 请求成功返回后台数据
      resolve(res.data)
    }).catch((error) => {
    
    
      reject(error)
    })
  })
}

After completing the content packaging, you need to export the function in the file:

export {
    
    
  request,
  get,
  post
}

transfer
main.jsInject globally in the file:

// 封装axios primary
import axios from 'axios'
import {
    
     api } from './api'
import qs from 'qs'
// 默认的地址
axios.defaults.baseURL = api

At this point, we can freely call several network request methods exported from the above api in the vue page!

Guess you like

Origin blog.csdn.net/qq_44469200/article/details/103575647