axios(阿克休斯) 官网 : axios中文网|axios API 中文文档 | axios
axios是什么 : 一个js框架,用于发送ajax请求(底层使用XMLHttpRequest)
基本使用语法
1.axios基本使用
axios.get('url')
.then( res=>{ //请求成功 } )
.catch( err=>{ //请求失败 } )
.then( ()=>{ //请求完成. 无论成功还是失败 })
2. axios发送get请求
axios.get('url', { params:{key:value} } )
.then(res=>{ //请求完成} )
3. axios发送post请求
axios.post('url',{ key:value })
.then(res=>{ //请求完成} )
//基本使用
document.querySelector('.btn1').addEventListener('click',function(){
axios
.get('https://autumnfish.cn/api/joke/list?num=10')
.then( res=>{
//(1)res里面存储很多数据: 服务器响应数据、请求头、请求配置、请求xhr对象
console.log(res)
//(2)res.data : 服务器响应的数据,相当于xhr.responseText
console.log( res.data )
} )
.catch( err=>{
//请求错误
console.log( err )
} )
.then( ()=>{
//请求完成 : 无论成功还是失败,请求完成就会执行
console.log( '请求完成' )
} )
})
//点我发送get请求
document.querySelector('.btn2').addEventListener('click',function(){
axios.get('https://autumnfish.cn/api/joke/list',{
params:{num:10}
}).then( ({ data })=>{
//获取服务器返回的数据
// let data = res.data
// let { data } = res
console.log( data )
} )
})
//点我发送post请求
document.querySelector('.btn3').addEventListener('click',function(){
axios.post('http://www.liulongbin.top:3009/api/login',{
username:'1423543',
password:'afsfs'
})
.then( ({data})=>{
// let {data} = res
// res.data
console.log(data)
})
})
axios推荐使用方式
1.axios基本使用
axios.get('url')
.then( res=>{ //请求成功 } )
.catch( err=>{ //请求失败 } )
.then( ()=>{ //请求完成. 无论成功还是失败 })
2. axios发送get请求
axios.get('url', { params:{key:value} } )
.then(res=>{ //请求完成} )
3. axios发送post请求
axios.post('url',{ key:value })
.then(res=>{ //请求完成} )
4. axios推荐用法
axios({
method:'请求方法',
url:'请求路径',
data:{ post参数 },
params :{ get参数 }
}).then( res=>{ //请求成功 })
//基本使用
document.querySelector('.btn1').addEventListener('click', function () {
axios({
method: 'get',
url: 'https://autumnfish.cn/api/joke/list',
params: { num: 10 }
}).then(res => {
console.log(res)
})
})
//点我发送post请求
document.querySelector('.btn3').addEventListener('click', function () {
axios({
method: 'post',
url: 'http://www.liulongbin.top:3009/api/login',
data: {
username: 'admin',
password: '123456'
}
}).then(res => {
console.log(res)
})
})
链式语法原理了解
链式语法 : 对象可以连续调用方法
let obj = {
name:'千玺',
sex:'男',
age:18
}
//对象方法
obj.setName = function(str){
this.name = str
//返回自身
return this
}
obj.setAge = function(num){
this.age = num
return this
}
obj.setSex = function(str){
this.sex = str
return this
}
obj.setName('颜值担当').setAge(28).setSex('女')
console.log(obj)
全局配置请求头
由于除了登录和注册接口外,其他所有接口都需要身份认证(都需要我们提供令牌),所以我们可以在 request.js
中,全局配置请求头。
axios.defaults.headers.common['Authorization'] = localStorage.getItem('token')