Use of axios plugin in vue

In the development of a website project, the front-end needs to interact with the back-end personnel for product data. You can understand that: the back-end personnel in the project are like aircraft parts processors (the user is the producer), and the ui designer provides the molded product Drawings, and the front-end people assemble the aircraft with parts according to the design drawings!

Insert picture description here

In the project, developers need to exchange information and feedback information. What I'm talking about here is 前、后端数据交互. Take the vue project as an example :

axios

In the background interaction to obtain data, we usually use the axios plug-in library, which is based on promisethe httplibrary, which can run on the browser side and node.js. It has these advantages:

For example, intercepting requests and responses, canceling requests, converting json, client-side defense against XSRF, etc.

In the development project, everyone may have found out: There are many api interfaces in a project, as few as dozens, and as many as hundreds. It can't be filled in every page get()or is post()it? This way the code is redundant and inefficient. As a professional developer, we usually encapsulate the request ourselves. Let me know how I did it.

One, the packaging of axios

Install axiosplugin

npm install axios --save //这个就是安装axios的命令

The next step is to create a new requestdirectory and two files in the src file of the project : one is http.jsand the other is api.js. http.jsIt is used to encapsulate Axios and api.jsis used to manage our interface in a unified way.

Introduce

The first step is to introduce axios in http.js

import axios from 'axios'

Switching the environment
When we develop a project, there will be multiple environments, such as development environment, test environment, and production environment. axios.defaults.baseURLThe default request address can be set for axios.

//在开发环境中的测试 development
if(process.env.NODE_ENV == 'development') {
    
    
	axios.defaults.baseURL = 'http://192.168.0.1:3000/'
}
//在生产环境中的测试 production
if(process.env.NODE_ENV == 'production') {
    
    
	axios.defaults.baseURL = 'https://www.liulong520.cn.api/'
}
//还有一种环境 debug

Set response timeout time
By axios.defaults.timeoutsetting the default request timeout time. If the response time is exceeded, the user will be notified that the current request has timed out

//响应超时的时间
axios.defaults.timeout = 5000;

设置接口请求拦截
//接口请求拦截
axios.interceptors.request.use(
	config => {
    
    
		config.headers = {
    
     DeviceType : 'H5' } //设置响应头部
		return config
	}
)

Use post that promisereturns the axiosrequested result
:

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

get :

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

At this time, the http.jsinside is written. The following going to api.jsgo get the api interfaces.

Now it is the content in api.js. The
first thing is to api.jsintroduce the just encapsulated axios in

import {
    
    get,post} from '../request/http.js'
//get post 同时都要引入
然后就可以根据接口文档来进行数据的获取啦

//封装接口的方法
export function getAppIndex() {
    
    
	return get('api/app/recommend/appIndex')
}

export function getBanner() {
    
    
	return get('api/app/banner')
}

export function getTel() {
    
    
	return post('api/app/smsCode',{
    
    
			//这里用的是params传参,直接写{}就可,不用再声明params啦
			phone: 18386100096,
			code: '123456'
	})
}

Finally we can call in the page life cycle

mounted() {
    
    
	let res = await getAppIndex();
	
	//添加到数组
	this.startList = res.data.data.list
	
	// 轮播图列表
	var banner = await getBanner();
	// console.log('轮播图'+ banner)
	if (banner.data.code == 200) {
    
    
		this.bannerList = banner.data.data
	}

	// 手机验证码接口
	let Tel = await getTel();
},

End of sharing!
Reference: The idea and method of Axios encapsulation API interface in Vue

Guess you like

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