文章目录
axios的请求方法
方法 | 用途 | 备注 |
---|---|---|
get | 获取数据 | / |
post | 提交数据 | 表单提交+文件上传 |
put | 更新数据 | 所有数据推送到后端 |
patch | 更新数据 | 只将更改的数据推送到后端 |
delete | 删除数据 | / |
导包
import axios form ‘axios’
get请求:获取数据
# 第一种get请求:不带参数
axios.get('请求地址')
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(error)
})
# 第二种get请求:路由中带参数
axios.get('请求地址/?id=123')
.then(res=>{
console.log(res.data)
})
.catch(err=>{
console.log(error)
})
# 第三种get请求:params方法
axios.get('请求地址',{
params:{
id:123
}
})
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(error)
})
post请求:提交数据
# 第一种post请求:传递普通参数
axios.post('请求地址',{
data:{name:'张三'}
})
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(error)
})
# 第二种post请求:传递图片等数据
let formdata = new FormData()
formdata.append('key',document.getElementById('图片id').files[0])
axios.post('请求地址',{
data:formdata
})
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(error)
})
axios的通用写法
axios({
method:'请求方式'}),
url:'请求地址',
params:{name:'1'}, # 传递get,delete参数信息
data:{name:'1'}, # 传递post,put,patch,delete参数信息
})
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(error)
})
注意:使用params方法时,请求接口时参数是放在RUL里传递的,而使用data方法就不会,根据实际情况使用