axios的使用方法
1.安装
使用 npm:
$ npm install axios
使用 bower:
$ bower install axios
使用 yarn:
$ yarn add axios
使用 jsDelivr CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
使用 unpkg CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2.基本使用
document.getElementById("btn1").onclick=()=>{
//直接调用axios发送请求
// axios(config)
axios({
// 所用的方法
method:"post",
// 发送请求的地址
url:"http://localhost:3000/students",
//要发送的数据
data:{
name:"唐僧",
age:18,
gender:"男",
address:"女儿国"
}
}).then((result)=>{
// result 接收服务器所返回的数据
console.log(result.data);
}).catch((err)=>{
// 错误信息
console.log("出错了");
})
}
document.getElementById("btn2").onclick=function(){
axios({
method:"get",
url:"http://localhost:3000/students",
}).then((result)=>{
// axios默认只会在响应状态未2xx时才会调用then
// result是axios封装过的
console.log(result);
}).catch((err)=>{
console.log("出错了"+err);
})
}
3.axios的配置对象
url (必填,其他配置对象不填默认发post请求)
发送请求的地址
url:"http://localhost:3000/students",
baseURL
指定服务器的根目录,配合url使用
// baseURL 指定服务器的根目录
baseURL:"http://localhost:3000",
// 请求的地址
url:"students"
此效果等于以下代码
url:"http://localhost:3000/students"
method
请求方法,默认是get
method:"post"
headers
指定请求头
axios是非常智能的,他会根据发送的数据(data),自动识别所用的数据提交方式,一般是不需要程序员自己填写此配置对象
headers:{
"Content-type":"application/json"
}
四种常见的 POST 提交数据方式
值 | 描述 |
---|---|
application/x-www-form-urlencoded | 在发送前编码所有字符(默认) |
multipart/form-data | 不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。 |
application/json | 作为请求头告诉服务端消息主体是序列化的JSON字符串。除低版本的IE,基本都支持。 |
text/plain | 空格转换为 “+” 加号,但不对特殊字符编码。 |
data
请求体
data:"name=前端&height=180" // application/x-www-form-urlencoded 方式
data: {
name: "前端",
height: 180,
}
// application/json 方式
在填写完data后,axios会自动识别data,把请求头(header)自动设置
transfromRequest
用来处理请求数据(data)
它需要一个数组作为参数,数组可以接收多个函数,请求发送时多个函数会按照顺序执行
函数在执行时。会接收两个参数data和headers
transformRequest:[
function(){
console.log(data);
console.log(headers);
},
function(){
console.log(222);
}
]
当然,我们可以对data和headers进行修改,但是值得注意的时,第一个函数处理完data后需要return一下它,不然第二个函数是拿不到它的
transformRequest:[
function(data,headers){
//可以在函数中对data和header进行修改
data.name="axios"
return data
},
function(data){
console.log(data);
}
]
transformResponse
用来处理响应数据(服务器所返回的数据)
transformRequest:[
function(data,headers){
//可以在函数中对data和header进行修改
data.name="axios"
return data
},
function(data){
console.log(data);
}
]
params
与请求一起发送的 URL 参数
指定路径中的查询字符串
params:{
id:1,
name:"haha"
}
请求地址会变为:
http://localhost:3000/students?id=1&name=swk
timeout
请求过期的时间``(单位:毫秒)
timeout:1000
到指定时间,请求会自动取消