今日学习
ajax框架 axios 【jQuery】
1) 回忆jquery
底层接口
$.ajax({})
$.ajaxSetup({})
快捷接口
本质上是对于底层接口的封装
$.get(url,param,success)
$.post(url,data,success)
$.put(url,data,success)
$.delete(url,param,success)
如果发送的get/delete请求,请求参数称为param,一般这个参数是拼接在url中
如果发送的post/put请求,请求参数称为data,一般这个参数是存放在请求体中
请求体data可以进行编码后传输
Content-Type: application/x-www-form-urlencoded
jquery中ajax的默认形式,如果data为对象,jquery会自动将参数转换为查询字符串
Content-Type: application/json
如果想要发送json,1) 修改Content-Type。 2) 对data进行编码
场景:
vue实例
用户点击了保存按钮
methods:{
...mapActions(['saveOrUpdateArticle'])
}
this.saveOrUpdateArticle(this.form,function(){
当保存成功后,
1) 关闭模态框
2) 提示保存成功
3) 刷新列表
})
vuex状态机
actions:{
saveOrUpdateArticle(data,handler){
$.post(url,data,function(response){
handler(response)
})
}
}
2) axios
与jquery中的ajax类似,axios是用于封装底层的XMLHttpRequest【ajax】;不同的是axios是一个专一的ajax框架,axios是基于promise机制的框架,即可以运行到浏览器中也可以运行在nodejs,提供了请求响应的拦截器,在POST请求中默认将请求参数对象封装为json字符串,可以对响应信息进行二次封装
1. 底层接口
1) 直接通过axios底层函数发送请求
axios(config)
2) 先创建axios实例对象,在创建的时候可以添加一些默认的配置信息,这样所有的axios实例对象都具备这样的配置信息了。
let request = axios.create([config])
request.get()
3) 为axios配置默认值 , xxx表示config中的属性
axios.defaults.xxx
config是一个对象
{
url,
method,
baseURL, // 基路径,一个真正的请求应该是 baseURL + url, 【http://localhost:8888】【/article/findAll】
data, // 是放在请求体中被传递的参数,仅适用于'PUT', 'POST', and 'PATCH'
params, // 表示拼接在url后面的参数,参数格式查询字符串
headers // 表示请求头信息 Content-Type
timeout // 超时时间设定
withCredentials // false,表示是否携带cookie
responseType // 等同于jquery中的dataType,服务器返回的数据类型,默认为json
responseEncoding// 默认为utf-8
transfromRequest
transfromResponse
}
axios会将服务器端返回来的数据做一次封装,封装的时候将服务器端返回的数据放到data中
服务端数据格式
{
status:200, // 200 500 401 403
data: // 字符串,对象,数组
message:'' // 接口响应信息
timestamp: // 时间戳,表示接口响应时间
}
2. 便捷接口
axios.request(config)
axios.get(url[,config])
axios.post(url,data[,config])
axios.delete(url[,config])
axios.put(url,data[,config])
3. 拦截器
可以对所有的请求进行拦截
1) 请求拦截器
在请求发送之前拦截所有请求
axios.interceptors.request.user(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
})
2) 响应拦截器
在请求响应回来之前拦截响应
axios.interceptors.response.use(function(response){
return response;
},function(error){
return Promise.reject(error);
})
4. 全局默认配置
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-
www-form-urlencoded';