1、axiOS:是一个基于Promise的网络请求库。既可以在node.js(服务器端)使用,也可以在浏览器端使用 (1)在node.js中使用的原生的Http模块 (2)在浏览器中
1、axiOS:是一个基于Promise的网络请求库。既可以在node.js(服务器端)使用,也可以在浏览器端使用
(2)在浏览器中使用的XMLHttpRequest
2、Vue中的使用方法
(1)安装:npm install axios
(2)引用方法:
原生的方式(不推荐使用)
axios({
url:'http://127.0.0.1:9001/students/test', //远程服务器的url
method:'get', //请求方式
}).then(res=>{
this.students = res.data
}).catch(e=>{
console.error(e);
})
//缺点:每个使用axios的组件都需要导入
注:axios对服务端数据的封装
在项目的main.js文件中导入axios,将其写入Vue的原型中(推荐使用)
import axios from "axios";
Vue.prototype.$http = axios
在组件中通过this.$http的方式使用
this.$http.get('http://127.0.0.1:9001/students/test').then(res=>{
this.students = res.data
}).catch(e=>{
console.log(e)
})
缺点:只能在vue2使用,vue3中不能用
将axios单独封装到某个配置文件中(在配置文件中单独封装axios实例)
(1)配置文件:axiosapi.js
import axios from "axios";
const axiosApi = axios.create({
baseURL:'http://127.0.0.1:9001', //基础地址
timeout:2000 //连接超时的时间(单位:毫秒)
})
export default axiosApi //axiosApi是axios的实例
(2)使用:
import $http from '../config/axiosapi'
$http.get('/students/test').then(res=>{
this.students = res.data.info
}).catch(e=>{
console.log(e)
})
优点:既可以在vue2中使用,也可以在vue3中使用
3、axios的不同请求方式向服务器提交数据的格式:
(1)get请求:服务器端通过req.quert参数名来接收
直接将请求参数绑定在url地址上
let str = '张三'
$http.get('/students/test/?username='+str).then(res=>{
this.students = res.data.info
}).catch(e=>{
console.log(e)
})
通过params方式进行提交
let str = '张三'
$http.get('/students/test',{
params:{
username:str
}
}).then(res=>{
this.students = res.data.info
}).catch(e=>{
console.log(e)
})
(2)post方式请求:服务器端通过req.body.参数名获取数据
let str = '张三'
$http.post('/students/test',{
username:str
}).then(res=>{
this.students = res.data.info
}).catch(e=>{
console.log(e)
})
(3)put方式请求:和post方式一样
(4)delete方式请求:和get方式一样
到此这篇关于Vue封装axios的示例讲解的文章就介绍到这了,更多相关Vue axios内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Vue封装axios的示例讲解
本文链接: https://www.lsjlt.com/news/177319.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0