Global encapsulation of api in vue--secondary encapsulation of axios

Table of contents

Why encapsulate axios

 1. The first step is to create a new utils/request.js file in the src directory. The content of the file is as follows:

2. Encapsulation and use of api

2.1 Create a new api/index.js file in the src directory, the file content is as follows:

 Axios uses data, params, headers to pass parameter difference

2.2 Use the packaged api


Why encapsulate axios

axios Everyone is very clear, a library that can be used for 客户端or  服务端to send httprequests.

In the actual development project, the network request basically uses the axios network request tool, but simply using the image axios.get('http://xxxxx.com')to request the interface, as the project grows larger, more and more pages, and more and more perfect functions, we are bound to write a lot of The axios request is written like this every time, which is time-consuming and laborious, and it is not convenient for unified management. Therefore, it is necessary to re-encapsulate axios to save time, effort, and worry when we develop projects.

This is how to use axios before encapsulation. If you modify the domain name later, it will be troublesome:

  axios.get('https://api.apiopen.top/api/getImages?id=',param).then((res) => {
         this.shuju=res.result.list;
         console.log(this.shuju)
       });

 1. The first step is srcto create a new file in the directory utils/request.js. The content of the file is as follows:

//首先引入axios
import axios from 'axios'
//然后通过create方法来创建一个请求服务
//然后create方法内有一些配置项,比如接口域名`baseURL`、接口请求超时时间`timeout`
//接口url`url`
//接口请求方式`method`等等,需要我们按需传入
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL, // 完整的api地址 = 接口域名+ 接口路径
// 完整url = 服务根url + 请求url拼接的; 服务根url来源于全局变量;请求url来源于api函数的url参数。
  // withCredentials: true, // 跨域请求时发送cookie
  timeout: 5000 // 请求超时时间 5s,请求超时
})
//下面会定义两个拦截器,分别是 `请求拦截器`,`响应拦截器`
//`请求拦截器`是前端请求后端接口前处理的一些逻辑,比如开启loading,配置header请求头等等
//`响应拦截器`就是后端响应我们前端,返回回来的数据,比如我们可以在这响应拦截器内拿到status Code
//拿到后端接口返回的code,关闭loading、根据code码处理一些详细的逻辑等等一系列操作
//request interceptor   请求拦截器  
service.interceptors.request.use(
  config => {
    // do something before request is sent。在发送请求之前做一些事情
  // 请求之前的设置
    // 添加请求头信息,可以根据需要自行选择,也可以不要
    // 例如请求头加入“tken”键 
    config.headers['token'] = "xxxxxx"
    return config
  },
  error => {
    // do something with request error// 请求错误时
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// response interceptor  响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.// 在这里限定了返回的必须要有返回码——code键,且返回码不为200时视为请求结果错误的 
    if (res.code !== 200) {
  // 这是错误信息提示
// 如果返回值有键-message,则错误信息是自定义的返回信息值,否则只提示'Error'
      alert(res.message || 'Error')
// 你也可以加入其它一些返回码的判断,也可以根据某些返回码跳转到某些页面
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    alert(res.message || 'Error')
    return Promise.reject(error)
  }
)

// 最后暴露我们声明的 service 服务
export default service

2. Encapsulation and use of api

  • The api request method also needs to be encapsulated. The encapsulation process is as follows
  • 2.1 srcCreate a new file in the directory api/index.js, the content of the file is as follows:

 import request from '../utils/request';
//登录接口,post方式传参用data
export function login(data) {
  return request({
    url: '/api/login',
    method: 'post',
    data
  })
}
//获取xx列表接口,get方式传参用params
export function getList(params) {
  return request({
    url: '/api/getList',
    method: 'get',
    params
  })
}

 Axios uses data, params, headers to pass parameter difference

There are two ways to pass parameters in vue routing, namely queryand params; query is plain text, and params is hidden;

1. What is the difference between params and data? Summary:

  • The difference between params and data, that is, the difference between get and post requests, the basics of HTTP protocol
  • The get request parameters are carried on the url, and params must be used
  • post request is body data use data

params is added to the request string of the url and is generally used for get requests.

The object parameter name and value of params, the source code of axios will splice the parameters and values ​​in ulr? Splicing later to the background (query query string)

data is added to the request body (body), and is generally used for post requests.

The object parameters and values ​​of data, the axios source code will splice the parameters and values ​​into the request body (body parameters)

2. Two request methods:

1) get request

axios({
    method: 'GET',
    url: 'xxxxx',
    params: param,
  })
或者 
axios({
    method: 'GET',
    url: '/xxx?message=' + msg,
  })

No matter which method is used for the get request, the last parameter will be placed on the path.
Using param is just axios serializing this parameter for you and splicing it on the url.

2) post request

axios({
    method: 'POST',
    url: '/xxxxx',
    data: param,
  })
  或者
 axios({
    method: 'POST',
    url: '/xxxxx',
    params: param,
  })
  • data form

The case code is as follows:

 method: 'POST',
    url: '/xxxxx',
    data: param,
  })

What is passed using data is an object, and what you see  in the browser--console isrequest payload

The view sources of the parameters are as follows:

insert image description here

  • params form

This is passed in the form of an object, the case code is as follows:

 axios({
    method: 'POST',
    url: '/xxxxx',
    params: param,
  })

Analysis of browser results:

 View view sourcer as follows:

3)headers

Mount the passed parameters to the request header

 import store from '@/store'
// 获取用户信息接口
export const getUserInfoAPI = function() {
  return request({
    url: '/my/userinfo'
    // method不写默认为‘get’方法请求
    // 传递给后台:params(查询字符串query),data(请求体body),headers(请求头)
    headers: {
      // this.$store.state.token这里的this不是组件对象,不能用this.$store拿到store对象
      Authorization: store.state.token
    }
  })
}

 For details, please refer to this article: The way axios passes parameters (the difference between data and params)_twinkle||cll's blog-CSDN blog_axios params

  • 2.2 Use the packaged api

  • On the required page, such as our login page, we need to call the login interface, we will use it like this
  • When used in the page, introduce the login method, remember to use {} in the method, {username:'admin',password:"123456"} in the method are the parameters I want
//首先第一步要用import导入进来我们的登录接口
import { login } from '../api/index'

//然后直接调用login方法
login({username:'admin',password:"123456"}).then(res=>{
      console.log(res);
})
  • Create a new api.index.js file under api, and refer all interfaces to the entry

  • The main.js file mounts api globally (httpApi is self-named)

  • page interface call

Guess you like

Origin blog.csdn.net/coinisi_li/article/details/129031194