Vue - axios 请求后台接口的几种方式
Vue 中 axios 的使用
- 一. 介绍
- 二. vue项目中 中安装使用 axios
- 三. axios 请求接口的五种方式
- 1.get 方式
- 1.1 不带参数请求接口
- 1.2 带参数请求接口(params传参)
- post 方式
- 2.1 不带参数请求接口
- 2.2 带参数请求接口
- put 方式
- patch 方式
- delete 方式
一. 介绍
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
了解更多:https://www.kancloud.cn/yunye/axios/234845
二. vue项目中 中安装使用 axios
- 安装
axios
npm install axios
在
main.js
页面引入axios
,并配置默认请求接口//配置axios,设置默认请求接口地址
import axios from 'axios'
axios.defaults.baseURL="http://xxxx:9810"
Vue.prototype.$axios=axios
组件中使用
this.$axios.post('/url接口地址').then((res)=>{
console.log(res)
})
三. axios 请求接口的五种方式
- get:一般多用于获取数据
- post:主要提交表单数据和上传文件
- put:对数据全部进行更新
- patch:只对更改过的数据进行更新
- delete:删除请求
1.get 方式
1.1 不带参数请求接口
第一种方式
axios.get('url接口地址').then((res)=>{
console.log(res)
}),
第二种方式
axios({
method:'get',
url:'url接口地址',
}).then((res)=>{
console.log(res)
}),
1.2 带参数请求接口(params传参)
第一种方式
axios.get('url接口地址',{
params:{
id:1
}
}).then((res)=>{
console.log(res)
}),
const obj={
id:1
}
axios.get('url接口地址',{
params:obj
}).then((res)=>{
console.log(res)
}),
第二种方式
axios({
method:'get',
url:'url接口地址',
params:{
id:1
},
}).then((res)=>{
console.log(res)
}),
const obj={
id:1
}
axios({
method:'get',
url:'url接口地址',
params:obj,
}).then((res)=>{
console.log(res)
}),
2. post 方式
2.1 不带参数请求接口
第一种方式
axios.post('url接口地址').then((res)=>{
console.log(res)
}),
第二种方式
axios({
method:'post',
url:'url接口地址',
}).then((res)=>{
console.log(res)
}),
2.2 带参数请求接口
第一种方式
axios.post('url接口地址',{
id:1
}).then((res)=>{
console.log(res)
}),
const obj={
id:1
}
axios.post('url接口地址',obj).then((res)=>{
console.log(res)
}),
第二种方式
axios({
method:'post',
url:'url接口地址',
data:{
id:1
},
}).then((res)=>{
console.log(res)
}),
const obj={
id:1
}
axios({
method:'post',
url:'url接口地址',
data:obj,
}).then((res)=>{
console.log(res)
}),
3. put 方式
const obj={
id:1
}
axios.put('url接口地址',obj).then(res=>{
console.log(res)
})
4. patch 方式
const obj={
id:1
}
axios.patch('url接口地址',obj).then(res=>{
console.log(res)
}),
5. delete 方式
当写法参数为 params 时,请求接口时参数会放在URL里面
第一种方式
axios.delete('url接口地址',{
params:{
id:1
}
}).then(res=>{
console.log(res)
})
第二种方式
axios.delete('url接口地址',{
data:{
id:1
}
}).then(res=>{
console.log(res)
})
还没有评论,来说两句吧...