axios请求接口http_vue + axios---封装一个http请求

本文介绍如何在Vue项目中集成Axios库,并实现全局HTTP请求处理。包括安装Axios、自定义封装、设置请求拦截器及配置默认请求地址等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用vue开发时,官方推荐使用axios来请求接口

// axios官方地址

https://github.com/axios/axios

但是axios并不像 vue-resource 一样拥有install,即不能直接 Vue.use(axios) 来使用,所以需要我们自己根据axios来写一个具有install方法的Http库。

1.安装axios

npm install axios

2.创建Http.js文件

import axios from 'axios'

export default {

install (Vue) {

// install方法,向Vue实例中添加一个$http方法

Vue.prototype.$http = axios

Vue.$http = axios

},

$http: axios

}

export const Http = axios

3.引用

import Vue from 'vue'

import Http from './Http'

Vue.use(http)

如此,就可以在vue中直接使用axios了

4.axios拦截器

在开发过程中,会需要设置一些请求头,公共参数等,或者需要对请求结果进行统一处理(例如错误处理),这时候就可以用到axios拦截器

创建interceptor.js文件

import axios from 'axios'

let interceptor = ''

export const myInterceptor = interceptor

// 设置请求拦截器

export const setInterceptor = function (response) {

axios.interceptors.request.use((config) => {

config.headers.Authorization = token //设置请求头Authorization

config.headers.Accept = 'application/json' //设置请求头Accept

/*

具体配置需要根据实际开发情况来配置

*/

return config

})

}

// 移除请求拦截器

export const clearInterceptor = function () {

axios.interceptors.request.eject(myInterceptor)

}

ps:上例只示范了axios的请求拦截,回复拦截时同样的处理方式

ps:在interceptor中暴露myInterceptor、setInterceptor与clearInterceptor 的原因是方便随时取消与设置

5.设置axios默认请求地址

axios.defaults.baseURL = 'http://172.0.0.1'

虽说几乎都是使用webpack代理的方式来配置请求地址,但此方式依然有时会用到

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值