前端必懂!Axios!

安装

npm i axios vue-axios -S(可以加上--save-exact 作为精确版本安装)

import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
// 设置通用的请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

提供的API

request(config)
get(url, config)
delete(url, config)
head(url, config)
options(url, config)
post(url, data, config)
put(url, data, config)
patch(url, data, config)
// 同时调用两个接口
all()

axios()

axios({
		url: 'url',
		method: 'get', // 'post'
		// 'get'使用params
		params: {
			key: val
		},
		// 'post'使用data
		data: {
			key: val
		},
		headers: {
			key: val
		}
	})
	.then(res => {})
	.catch(err => {})

get()

axios.get('url', {
		// 传参
		params: {
			key: value
		},
		// 请求头
		headers: {
			key: value
		}
	})
	.then(res => {})
	.catch(err => {})

post()

axios.post('url', {
		// 传参
		key: value
	}, { // 请求头
		headers: {
			key: value
		}
	})
	.then(res => {})
	.catch(err => {})

request 拦截器

axios.interceptors.request.use(
	config => {
		if (store.state.token) {  // 判断是否存在token,如果存在的话,则每个http header都加上token
			config.headers.Authorization = `token ${store.state.token}`;
		}
		return config;
	},
	err => {
		// 请求失败的统一处理
		return Promise.reject(err);
	});

response 拦截器

axios.interceptors.response.use(
	response => {
    // 配置
		return response;
	},
	error => {
		if (error.response) {
			switch (error.response.status) {
				case 401:
					// 判断状态码进行处理
			}
		}
		return Promise.reject(error.response.data)   // 返回接口返回的错误信息
	});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值