Why encapsulate the axios request method, and how to encapsulate

Why encapsulate axios?

There are three stages in the development of the project

  1. Development environment (dev.abc.com)
  2. Test environment (text.abc.com)
  3. Production environment (abc.com)

When accessing interface data, for example, the product interface will be. 【域名】/api/v1/products
When the environment is different, just modify the domain name directly. This is the reason for the package request.

axios basic get request, post request

As the old saying goes , get requests to send data back, and post can carry data to send processing requests (usually used to submit forms or upload data),token

//axios.get 发起get请求
    //参数一表示请求地址
    //参数二表示配置信息
    //params  表示传递到服务器端的数据,已url参数的形式拼接在请求地址后面
    //{page:1,per:3}
    // 比如:http://jsonplaceholder.typicode.com/
    //最终生成:http://jsonplaceholder.typicode.com/?page=1&per=3
    // 其中?表示可选参数
    //headers  表示请求头
    getHandle(){
    
    
      axios.get('http://jsonplaceholder.typicode.com/',{
    
    
         params:{
    
       //注意,params和headers是固定字符
           page:3,
           per:2
         },
        headers:{
    
    }
      })
      .then(res=>console.log(res))
    },
    postHandle(){
    
    
      //post请求传递三个参数
      //请求地址
      //请求数据,请求配置,
      //axios默认发送的数据是json格式的
      //配置信息
      //headers
      //content-type:'application/json' 默认
       axios.post('http://open.qunar.com/',{
    
    
         userName:'xiaoming',
         password:'112132'
       },{
    
    })
      .then(res => console.log(res))
      .catch(err=>console.log(err))
    },

How to encapsulate axios request

First create a request.js file

import axiox from 'axios'

const instance =axiox.create({
    
    
    baseURL:'http://jsonplaceholder.typicode.com/',//baseURL会在发送请求的时候拼接在url参数的前面
    timeout:5000
})

//请求拦截
//所有的网络请求都会先走这个方法
// 添加请求拦截器,所有的网络请求都会先走这个方法,我们可以在它里面为请求添加一些自定义的内容
instance.interceptors.request.use(function (config) {
    
    
    // 在发送请求之前做些什么
    console.log('全局请求拦截')
    console.log(config)
    console.groupEnd()
    config.headers.token='12343'
    return config;
}, function (error) {
    
    
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
//此处可以根据服务器的返回状态码做响应的处理
//404 404 500
instance.interceptors.response.use(function (response) {
    
    
    // 对响应数据做点什么
    console.log('全局响应拦截')
    console.log(response)
    console.groupEnd()
    return response;
}, function (error) {
    
    
    // 对响应错误做点什么
    return Promise.reject(error);
});

export function get(url,params) {
    
    
    return instance.get(url,{
    
    
        params
    })
}

export function post(url,data) {
    
    
    return instance.post(url,data)
}

export  function del(url) {
    
    
    return instance.delete(url)
}

export  function put(url,data) {
    
    
    return instance.put(url,data)
}

Is it very long, a little ignorant, it’s okay, let’s explain one by one,
first, it’s a simple getrequest package

const instance =axiox.create({
    
    
    baseURL:'http://jsonplaceholder.typicode.com/',//baseURL会在发送请求的时候拼接在url参数的前面
    timeout:5000
})
export function get(url,params) {
    
    
    return instance.get(url,{
    
    
        params
    })
}

The address here baseURLwill be getautomatically spliced when the packaged party is called

import  {
    
     get} from '../utils/request'//导入封装的request文件
getByMineHandle(){
    
      //调用get方法
	 get('/api/v1/products',{
    
    })
	  .then(res=>{
    
    
		  console.log('成功',res)
	  })
	  .catch(err=>{
    
    
		  console.log('错误',err)
	  })
}

Global request interception will first intercept and add custom data when all requests are sent.
Here a custom tokenvalue is added
( tokenequivalent to the client's ID card)

//请求拦截
//所有的网络请求都会先走这个方法
// 添加请求拦截器,所有的网络请求都会先走这个方法,我们可以在它里面为请求添加一些自定义的内容
instance.interceptors.request.use(function (config) {
    
    
    // 在发送请求之前做些什么
    console.log('全局请求拦截')
    console.log(config)
    console.groupEnd()
    config.headers.token='12343'
    return config;
}, function (error) {
    
    
    // 对请求错误做些什么
    return Promise.reject(error);
});

Global response interception will trigger the corresponding data operation when the response is received. The response can be processed according to the status code returned by the server (404,401,403...)

instance.interceptors.response.use(function (response) {
    
    
    // 对响应数据做点什么
    console.log('全局响应拦截')
    console.log(response)
    console.groupEnd()
    return response;
}, function (error) {
    
    
    // 对响应错误做点什么
    return Promise.reject(error);
});

Guess you like

Origin blog.csdn.net/weixin_44348028/article/details/108504471