Axios packaging and interface management in vue


Preface

Tip: The following is the content of this article, the following cases are for reference

1. Packaging of axios?

In the vue project, we usually use axios to interact with the background to obtain data. It has many excellent features, such as intercepting requests and responses, canceling requests, converting json, and defending XSRF on the client side. It is a promise-based http library that can be run on the browser side and node.js. But here, let's not consider node.js. If you don’t know much about axios, you can refer to the axios documentation.

axios document address: https://www.npmjs.com/package/axios

Generally, I create a request folder in the src directory of the project, and then create a http.js and an api.js file in it. The http.js file is used to encapsulate our axios, and api.js is used to manage our interface uniformly.

Second, use steps

1. Install axios

npm install axios; //

2. New http.js (used to encapsulate axios)

Generally, I create a request folder in the src directory of the project, and then create a http.js and an api.js file in it. The http.js file is used to encapsulate our axios, and api.js is used to manage our interface uniformly.

Introduce axios

The code is as follows (example):

import axios from 'axios'; 

The url network request data used here.

Environment switch

Our project environment may have a development environment and a production environment. The default request address of axios can be set through axios.defaults.baseURL.

// 环境切换
//开发环境(development) 中用到的是测试接口 生产环境 (production)中用的是真实接口
if(process.env.NODE_ENV=='development'){
    
    
    axios.defaults.baseURL='http://120.53.31.103:84/api/app'
}
if(process.env.NODE_ENV=='production'){
    
    
    axios.defaults.baseURL='https://wap.365msmk.com/'
}

Set request timeout

//设置请求超时时间
axios.defaults.timeout=5000;

Request interception and response interception

Request interception:We can intercept a request before sending the request. Why should we intercept it? For example, some requests need to be accessed after the user logs in, or when post requests, we need to serialize (process) the data we submit. At this time, we can perform an interception before the request is sent to perform the operation we want.
Request interception:Response interception is actually easy to understand, that is, the data returned to us by the server, we can do some processing on it before we get it. For example, the above thought: If the status code returned by the background is 200, the data is returned normally, which is mainly an operation of adjusting the login page after the error is processed and the login page is not logged in or after the login expires.

// 请求拦截
axios.interceptors.request.use(
    config=>{
    
    
        config.headers={
    
    DeviceType:'H5'}//请求头的设置,根据需要写入
        return config;
    }
)
// 响应拦截
axios.interceptors.response.use(
    response=>{
    
    

     },
     error =>{
    
    
         if(error.response.status){
    
    

        }
    }

 )

Encapsulate get and post methods

//使用promise返回axios请求的结果 (promise)
export function get(url,params){
    
    
    return new Promise((resolve,reject)=>{
    
    
        axios.get(url,{
    
    
            params:params
        }).then(res=>{
    
    
            resolve(res);
        }).catch(err=>{
    
    
            reject(err)
        })
    })
}

export function post(url,params){
    
    
    return new Promise((resolve,reject)=>{
    
    
        axios.post(url,{
    
    params:params}
    ).then(res=>{
    
    
        resolve(res.data);
    }).catch(err=>{
    
    
        reject(err.data);
    })
})
};

2. New api.js (unified management of api)

Create a new api.js, and then store all our api interfaces in this file.

  • Introduce encapsulated get and post methods in api.js
import {
    
    get,post} from '../http/http.js';
  • Package interface instance (throw directly)
export function getBanners(){
    
    
   return get('/banner')
}

export function teacherDetail(id){
    
    
   return get('/teacher/'+id);
}
export function courseChapter(params){
    
    
   return post('/courseChapter',params)
   }
  • The page can call our api interface like this
async mounted(){
    
    
			var cid=this.$route.query.id;
			var classDetails=await classDetail(cid);
			if(classDetails.data.code==200){
    
    
			console.log(classDetails);
			this.classDetail=classDetails.data.data;	
			}
				}

If this blog is helpful to you, I hope you can call me (Follow me)~

Please leave a message for other questions~

Guess you like

Origin blog.csdn.net/weixin_48787059/article/details/108954996