vue项目实践-添加axios封装api请求
2024-10-19 04:29:19
安装 axios
npm install axios --save
创建实例 (utils/fetch.js)
axios 默认提交格式为:application/json
可使用 qs 模块(需要安装)转换后提交格式为 application/x-www-form-urlencoded
通过设置 transformRequest 属性 data => qs.stringify(data)
可以正常表单形式提交
import axios from 'axios'
const instance = axios.create({
baseURL: 'apiBaseUrl', // api的base_url
timeout: 10000 // 请求超时时间
// transformRequest: data => qs.stringify(data) //
})
// request拦截器
instance.interceptors.request.use(
e => {
e.params = e.params || {}
e.headers = e.headers || {}
//set 默认值
return e
},
error => ({ status: 0, msg: error.message })
)
// respone拦截器
instance.interceptors.response.use(
response => {
const resp = response.data
if (response.status === 200) {
return resp
}
return resp
},
error => {
console.log('err' + error) // for debug
return Promise.reject(error)
}
)
export default instance
将 api 请求封装到 api 文件夹下
在 api 文件中新建接口模块并使用 axios 实例(utils/fetch.js)
src/api/api_test.js
import request from '@/utils/fetch'
export function test(data) {
return request({
url: '/test',
method: 'post',
data: data
})
}
使用的时候,可通过引入 api/模块.js 调用方法,也可以通过安装插件的形式将 api 接口扩展到 vue 实例中,使其可以更方便的在项目中使用
以 test 模块为例创建一个$api 扩展
src/api/index.js
import * as api_test from './test'
const apiObj = {
api_test
}
const install = function(Vue) {
if (install.installed) return
install.installed = true
Object.defineProperties(Vue.prototype, {
$api: {
get() {
return apiObj
}
}
})
}
export default {
install
}
在 main.js 安装 $api 扩展:
import api from './api'
Vue.use(api)
在项目中调用:this.$api.api_test.test().then(resp=>{...}).catch(()=>{...})
最新文章
- Parametric Curves and Surfaces
- PHP入门 - - 06-->;HTML的表格标签
- iOS Notification 的使用
- 一步一步搭建客服系统 (4) 客户列表 - JS($.ajax)调用WCF 遇到的各种坑
- Web 在线文件管理器学习笔记与总结(5)修改文件内容
- Unity3D ShaderLab Use Properties
- MyBatis学习总结_03_优化MyBatis配置文件中的配置
- 关于继承MonoBehaviour的一些记录
- c语言基础学习09_关于复合类型的复习
- javascript 原型及原型链详解
- Java爬虫爬取网站电影下载链接
- ADO.Net笔记整理(一)
- CodeForces - 867E Buy Low Sell High (贪心 +小顶堆)
- 安装GDB-ImageWatch ,在QT中查看图像
- win7安装vs2017时闪退
- Android开发之使用HttpURLConnection进行POST请求
- ubuntu普通账户获取root权限的方法以及su和su -的区别
- winform datagridview 不显示默认第一列 不显示未绑定列 数据源发生改变时自动更新 (转)
- Spring 一二事(8) - annotation 形式的 MVC
- 全连接BP神经网络
热门文章
- Qt-c++桌面编程报错:qt.qpa.plugin: Could not find the Qt platform plugin ";windows"; in ";";,已解决
- 用Mysql进行emp、dept、salgrade表的相关查询操作
- 快捷键打开Generate
- SpringBoot的Profiles根据开发环境和测试环境载入不同的配置文件
- golang slice 经典例题
- Docker使用docker-compose.yml构建Asp.Net Core和Mysql镜像并与Mysql数据库通信
- GitHub上受欢迎的Android UI Library
- Sentry部署
- Python @property 详解
- Linux多线程编程,为什么要使用线程,使用线程的理由和优点等