主流Ajax库-Axios
一、axios简要说明
1.axios是什么
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端。简单的理解就是ajax的封装
它本身具有以下特征:
- a.从浏览器中创建 XMLHttpRequest
- b.从 node.js 发出 http 请求
- c.支持 Promise API
- e.拦截请求和响应
- f.转换请求和响应数据
- g.取消请求
- h.自动转换JSON数据
- i.客户端支持防止 CSRF/XSRF
2.安装
使用 npm:
$ npm install axios
使用 bower:
$ bower install axios
使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
3.GET与POST请求
- GET请求案例
GET是默认的请求方式
// get()请求方式
axios.get('https://autumnfish.cn/api/joke/list?num=1',{
// axios的get属性里的数据用params封装起来,
params:{
name:'xinxin',
age:20
}
}).then(function(Response){
// axios的then回调函数执行正确的数据
console.log(Response);
}).catch(function(Error){
// axios的catch回调函数执行错误的数据
console.log(Error);
});
注意: get请求会把params中的键值对拼接成urlencode格式的字符串,然后以问号传递参数的形式,传递给服务器。
- POST请求
// post() 请求方式
axios.post('https://autumnfish.cn/api/joke/list/',{
name:'xinxin',
age:20
}).then(function(Response){
// axios的then回调函数执行正确的数据
console.log(Response);
}).catch(function(Error){
// axios的catch回调函数执行错误的数据
console.log(Error);
});
注意: get请求会把params中的键值对拼接成urlencode格式的字符串,然后以问号传递参数的形式,传递给服务器。
- promise是什么?
1、主要用于异步计算
2、可以将异步操作队列化,按照期望的顺序执行,返回符合预期的结果
3、可以在对象之间传递和操作promise,帮助我们处理队列
4.关于请求返回的数据
请求数据返回的是一个对象。
- config
基于axios发送请求的时候做的配置项 - data
从服务器获取的响应主体内容 - headers
从服务器获取的响应的头信息 - request
创建的Ajax实例 - status
状态码 - statusText
状态码的描述
5.axios的请求合并以及参数配置
同时请求多个,只有当这几个请求同时成功才做响应。其返回结果为一个数组。
<script>
// var sendArry = [
// axios.get('https://autumnfish.cn/api/joke/list?num=1'),
// axios.get('https://autumnfish.cn/api/joke/list?num=1'),
// ]
// axios.all(sendArry).then((res)=>{
// console.log(res);
// });
var sendArry = [
axios.get('https://autumnfish.cn/api/joke/list?num=1'),
axios.get('https://autumnfish.cn/api/joke/list?num=1'),
]
axios.all(sendArry).then(axios.spread((resA,resB)=>{
// 传入参数分别对应请求结果
console.log(resA);
console.log(resB);
}));
6.请求配置
常用的修改默认配置的方式
axios.defaults.baseURL = 'https://domain.com'
1
自定义成功失败规则
axios.defaults.validateStatus: function (status) {
return /^(2|3)\d{2}$/.test(status) // default
}
123
以上表示,当返回状态码为2xx或3xx都为成功,则都会执行then方法。
设置默认超时时间
axios.defaults.timeout = 3300;
1
设置默认请求头
axios.defaults.headers = {
key:'value'
}
7.设置响应拦截器
axios.interceptors.response.use(function success(result){
// 响应成功时
// 如下配置表示 只返回响应返回来的data即响应主体
return result.data
},function error(){
// 响应成功时
})
8.完整的请求配置
下面是所有可用的请求配置项,只有url
是必填,默认的请求方法是GET
,如果没有指定请求方法的话。
{
// `url` 是请求的接口地址
url: '/user',
// `method` 是请求的方法
method: 'get', // 默认值
// 如果url不是绝对路径,那么会将baseURL和url拼接作为请求的接口地址
// 用来区分不同环境,建议使用
baseURL: 'https://some-domain.com/api/',
// 用于请求之前对请求数据进行操作
// 只用当请求方法为‘PUT’,‘POST’和‘PATCH’时可用
// 最后一个函数需return出相应数据
// 可以修改headers
transformRequest: [function (data, headers) {
// 可以对data做任何操作
return data;
}],
// 用于对相应数据进行处理
// 它会通过then或者catch
transformResponse: [function (data) {
// 可以对data做任何操作
return data;
}],
// `headers` are custom headers to be sent
headers: {'X-Requested-With': 'XMLHttpRequest'},
// URL参数
// 必须是一个纯对象或者 URL参数对象
params: {
ID: 12345
},
// 是一个可选的函数负责序列化`params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// 请求体数据
// 只有当请求方法为'PUT', 'POST',和'PATCH'时可用
// 当没有设置`transformRequest`时,必须是以下几种格式
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer
data: {
firstName: 'Fred'
},
// 请求超时时间(毫秒)
timeout: 1000,
// 是否携带cookie信息
withCredentials: false, // default
// 统一处理request让测试更加容易
// 返回一个promise并提供一个可用的response
// 其实我并不知道这个是干嘛的!!!!
// (see lib/adapters/README.md).
adapter: function (config) {
/* ... */
},
// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
// This will set an `Authorization` header, overwriting any existing
// `Authorization` custom headers you have set using `headers`.
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// 响应格式
// 可选项 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // 默认值是json
// `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// 处理上传进度事件
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// 处理下载进度事件
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// 设置http响应内容的最大长度
maxContentLength: 2000,
// 定义可获得的http响应状态码
// return true、设置为null或者undefined,promise将resolved,否则将rejected
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects` defines the maximum number of redirects to follow in node.js.
// If set to 0, no redirects will be followed.
// 最大重定向次数?没用过不清楚
maxRedirects: 5, // default
// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
// and https requests, respectively, in node.js. This allows options to be added like
// `keepAlive` that are not enabled by default.
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' defines the hostname and port of the proxy server
// Use `false` to disable proxies, ignoring environment variables.
// `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
// supplies credentials.
// This will set an `Proxy-Authorization` header, overwriting any existing
// `Proxy-Authorization` custom headers you have set using `headers`.
// 代理
proxy: {
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` specifies a cancel token that can be used to cancel the request
// (see Cancellation section below for details)
// 用于取消请求?又是一个不知道怎么用的配置项
cancelToken: new CancelToken(function (cancel) {
})
}
二、fetch的基础语法
1.fetch概念
fetch不是Ajax,它诞生的目的是为了代替Ajax,它是js中内置的API。
基于fetch可以实现客户端和服务端的信息通信
由于fetch是2018年提出,因此存在浏览器兼容问题。
fetch('https://v1.hitokoto.cn', {
method: 'GET',
}).then(result => {
console.log(result);
});
2.fetch和ajax 的主要区别
1、fetch()返回的promise将不会拒绝http的错误状态,即使响应是一个HTTP 404或者500
2、在默认情况下 fetch不会接受或者发送cookies
1.fetch概念
fetch不是Ajax,它诞生的目的是为了代替Ajax,它是js中内置的API。
基于fetch可以实现客户端和服务端的信息通信
由于fetch是2018年提出,因此存在浏览器兼容问题。
fetch('https://v1.hitokoto.cn', {
method: 'GET',
}).then(result => {
console.log(result);
});
2.fetch和ajax 的主要区别
1、fetch()返回的promise将不会拒绝http的错误状态,即使响应是一个HTTP 404或者500
2、在默认情况下 fetch不会接受或者发送cookies