赞
踩
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 Node.js 中。简单的讲就是可以发送 Get、Post 请求。
诸如 Vue、React、Angular 等前端框架都可以使用 Axios,由于他们不操作 DOM,所以就不必须引用 jQuery。如果你的项目里面用了 jQuery,此时就不需要多此一举了,jQuery 里面本身就可以发送请求($.get(URL,data,function(data,status,xhr),dataType))。
几个易混淆的概念
注:一两句话不可能讲清楚他们的区别,待后续再慢慢一一展开介绍吧,如有不准确的描述,请评论区指正。
参考:你知道Ajax、Fetch、Axios三者的区别吗? ajax、Promise、axios总结
// 1、安装 Axios 库 | |
// 在项目文件根目录下打开命令行,输入如下语句 | |
> npm install axios | |
// 2、js 文件中引入 | |
import axios from 'axios'; | |
// 3、直接通过关键字 axios 发送 http 请求 | |
// Get 请求 | |
axios({ | |
method: 'get', | |
url: 'URL文本' | |
}).then(({data}) => { | |
// 。。。 | |
}).catch((err) =>{ | |
console.log("catch-err:",err); | |
}).finally(() =>{ | |
// 。。。 | |
}) | |
// Post 请求 | |
axios({ | |
headers:{'content-type':'application/json'}, | |
method: 'post', | |
url: 'URL文本', | |
data:JSON.stringify({"dataid":dataid}) | |
}).then(({data}) => { | |
console.log("then-data:",data); | |
}).catch((err) =>{ | |
console.log("catch-err:",err); | |
}).finally(() =>{ | |
// 。。。 | |
}) |
@* 1、引用 js 包的 CDN *@ | |
<script src="https://unpkg.com/axios/dist/axios.min.js"></script> | |
@* 2、通过关键字 axios 发送 http 请求 *@ | |
<script> | |
// 调用方法 message() 查看测试结果 | |
window.onload = function () { | |
// Get 请求 | |
axios.get('https://localhost:44360/api/Methodname', { | |
params: { | |
mingcheng: '网络科技' | |
}, | |
headers: { | |
'token': '1111', | |
} | |
} | |
).then(ret => { | |
console.log("get:", ret); | |
}) | |
// Post 请求 | |
axios.post('https://localhost:44360/api/Methodname', | |
{ | |
"id": "df332b50-4abf-4fe6-814b-6d330a9ecc73", | |
"gongsix": "线下" | |
}, | |
{ | |
headers: { | |
'token': '1111', | |
} | |
} | |
).then(ret => { | |
console.log("post:", ret); | |
}) | |
} | |
</script> |
另外,除了通过 CDN 引用 js 库外,还可以直接添加 js 文件到项目的静态文件夹 wwwroot,然后在 .cshtml 页面文件中用过路径引用。
简要的三个步骤如下:
3. 然后通过路径引用后,即可在 js 脚本中使用 axios。
@* 注意路径代表 wwwroot 文件夹中,要对应得上 *@ | |
<script src="~/js/axios/axios.min.js"></script> |
参数名 | 示例值 | 解释 |
url | '/user' | 用于请求的服务器 URL |
method | 'get' | 创建请求时使用的方法,默认 get |
baseURL | 'https://some-domain.com/api/' | 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL(URL 必须带有资源的完整信息,包含协议、主机、路径等部分) |
headers | {'X-Requested-With': 'XMLHttpRequest'} | 自定义请求头 |
params | { ID: 12345 } | URL 参数,会自动拼接到 URL 中 |
data | { firstName: 'Fred' } | 作为请求主体被发送的数据,适用于'PUT'、'POST'、'PATCH' 三个请求方法。在没有设置 transformRequest 时,必须是以下类型之一:string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams、浏览器专属:FormData, File, Blob、Nodejs专属:Stream |
timeout | 1000 | 请求超时的毫秒数(0 表示无超时时间),若超时请求将被中断 |
withCredentials | false | 跨域请求时是否需要使用凭证,默认 false |
responseType | 'json' | 服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json'-默认, 'text', 'stream' |
responseEncoding | 'utf8' | 数据编码类型,默认 utf8 |
maxContentLength | 2000 | 允许的响应内容的最大长度,设置为无限长度:Infinity |
以下列举三种写法:
// (调用型1)查询给定 ID 的 user 对象请求 | |
axios.get('/user?ID=12345') | |
.then(function (response) { | |
console.log(response); | |
}) | |
.catch(function (error) { | |
console.log(error); | |
}); | |
// (调用型2)另一种写法 | |
axios.get('/user', { | |
params: { | |
ID: 12345 | |
} | |
}) | |
.then(function (response) { | |
console.log(response); | |
}) | |
.catch(function (error) { | |
console.log(error); | |
}); | |
// (方法型)写法 | |
axios({ | |
method:'get', | |
url:'/data.json', | |
params:{ | |
id:'12345' | |
} | |
}).then((res)=>{ | |
console.log(res) | |
}) |
一般上传的数据分两种:form-data 表单提交(图片上传、文件上传)、application/json。
// 先定义一个入参 data | |
let data = { id : 12 } | |
// (调用型)写法 | |
axios.post('/post',data) | |
}).then((res)=>{ | |
console.log(res) | |
}) | |
// (方法型)写法 | |
axios({ | |
method:'post', | |
url:'/post', | |
data:data | |
}).then((res)=>{ | |
console.log(res) | |
}) |
关于 Post 请求的 Content-Type:
当我们直接把入参填入 json 对象,丢给后端接口,此时 Content-Type 就自动为:application/json;charset=UTF-8。
当我们把 json 对象转为 FormData 类型,如下:
let data = { id : 12 } | |
let formData = new FormData() | |
for(let key in data){ | |
formData.append(key,data[key]) | |
} |
再将 formData 发送到后端,此时Content-Type 就自动变成:multipart/form-data; boundary=...... 。
// 请求列表,包含多个或多类型请求 | |
let sendAry = [ | |
axios.get('URL1'), | |
axios.get('URL2'), | |
axios.post('URL3') | |
]; | |
// 列表中的请求都完成后,才进行后续操作(可以基于ALL实现) | |
axios.all(sendAry).then(result => { | |
console.log(result); // 输出是一个数组,分别存储每一个请求的结果 | |
let [resA, resB, resC] = result; | |
}); |
在请求或响应被 then 或 catch 处理前拦截它们。
请求拦截器
axios.interceptors.request.use( | |
config=>{ | |
// 在发送请求前做的操作 | |
return config | |
}, | |
err=>{ | |
// 在请求错误的时候做的操作(此处错误,请求没有到后端) | |
return Promise.reject(err) // 这里返回一个 promise 对象 | |
} | |
) |
响应拦截器
axios.interceptors.response.use( | |
res=>{ | |
// 请求成功对响应数据进行处理 | |
return res | |
},err=>{ | |
// 响应错误做的操作(此处错误,到达后端后返回) | |
return Promise.reject(err) | |
} | |
) |
下面的代码是我们平时发送 Get 请求的标准形态,then 会执行请求成功后的操作,catch 用来捕获错误。我们前面拦截响应后,无论是请求还是响应的拦截器,他们的 err 返回的 promise 都会进入 catch 中。
axios.get().then().catch(err=>{}) |
取消拦截器
let inerceptors = axios.interceptors.request.use | |
(config=>{ | |
config.header = { | |
auth:true | |
} | |
return config | |
}) | |
// 如下:用 axios 全局去调用 interceptors,这样就取消拦截了 | |
axios.inerceptors.request.eject(interceptors) |
实例:通过拦截器控制登陆状态
// 登录状态,有 token,后端通过 headers 中的 token 进行身份校验 | |
let request = axios.create({}) | |
request.interceptors.request.use | |
(config => { | |
config.headers.token = '' // 发送请求前,统一将 token 加入到请求 headers | |
return config | |
}) | |
// 非登陆状态,无 token | |
let request2 = axios.create({}) |
全局配置
// 两个实例:(格式类同) | |
axios.defaults.timeout = 1000 // 全局配置请求时长(单位:毫秒) | |
axios.defaults.baseURL = 'https://api.example.com'; // 统一配置请求基础 URL |
实例配置
// 在创建实例时设置默认配置 | |
const instance = axios.create({ | |
baseURL: 'https://api.example.com' | |
}); | |
// 创建实例后可更改默认值 | |
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; |
优先级:请求配置 > 实例配置 > 全局配置
// 首先设置两种拦截器 | |
axios.interceptors.request.use( | |
config =>{ | |
return config | |
}, | |
err =>{ | |
return Promise.reject(err) | |
} | |
) | |
axios.interceptors.response.use( | |
res =>{ | |
return res | |
}, | |
err =>{ | |
return Promise.reject(err) | |
} | |
) | |
// 错误的获取 | |
axios.get('/data.json').then(res=>{ | |
console.log(res) | |
}) | |
.catch(err =>{ | |
console.log(err) // 所有错误处理都会进入此处 | |
}) |
具体的实践过程中,我们需要创建一个统一的错误处理,将所有的错误类型都放在拦截其中,方便我们后面调用接口时使用。
一个实例:
// 创建一个请求实例 | |
let instance = axios.create({}) | |
// 为请求实例添加请求拦截器 | |
instance.interceptors.request.use( | |
config =>{ | |
return config | |
}, | |
err =>{ | |
// 请求错误,一般 http 状态码以 4 开头,常见:401 超时,404 not found 多为前端浏览器错误 | |
return Promise.reject(err) | |
} | |
) | |
instance.interceptors.response.use( | |
res=>{ | |
return res | |
}, | |
err =>{ | |
// 响应错误,一般 http 状态码以 5 开头,500 系统错误,502 系统重启等,偏向于服务端返回的报错 | |
return Promise.reject(err) | |
} | |
) | |
// 使用 | |
instance.get('/data').then(res=>{ | |
console.log(res) | |
}) | |
.catch(err => { | |
console.log(err) | |
}) |
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。