axios网络请求

秒速五厘米 2021-07-24 21:01 777阅读 0赞
  1. axios网络请求
  2. 1、安装
  3. cnpm install axios -S
  4. 2、在main.js中引入
  5. import Axios from 'axios'
  6. 3、在main.js中将Axios挂载到Vue的原型上(可选)
  7. Vue.prototype.$axios=Axios
  8. 4axios配置
  9. axios({
  10. baseURL:'', 路径前缀,会将url的路径添加到后面
  11. url:'',
  12. method: 'get', 不写默认是 get
  13. timeout:n毫秒, 请求超时时间,若超过则取消
  14. transformRequest: [function (data, headers) { 允许在向服务器发送前,修改请求数据,只能用在 'PUT', 'POST' 'PATCH' 这几个请求方法
  15. data进行任意转换处理,必须返回一个字符串,或ArrayBuffer,或Stream
  16. return data;
  17. }],
  18. transformResponse: [function (data) { 在传递给then/catch前,允许修改响应数据
  19. return data;
  20. }],
  21. headers: {'X-Requested-With': 'XMLHttpRequest'}, 自定义请求头
  22. params: { 会被添加到url中的请求参数
  23. ID: 12345
  24. },
  25. paramsSerializer: function(params) { 参数序列化,如get请求传递的参数是个数组且报错,就可以使用这个选项将其序列化
  26. 不配置该参数,数组会默认转换为类似ids[]=1&ids[]=2&ids[]=3
  27. return qs.stringify(params, {arrayFormat: 'brackets'}) 转换成类似ids[]=1&ids[]=2&ids[]=3
  28. return qs.stringify(params, {indices: false) 转换成类似ids=1&ids=2&id=3
  29. return qs.stringify(params, {arrayFormat: 'indices'}) 转换成类似ids[0]=1&aids1]=2&ids[2]=3
  30. return qs.stringify(params, {arrayFormat: 'repeat'}) 转换成类似ids=1&ids=2&id=3
  31. },
  32. data:{作为请求主体被发送的数据,适用于这些请求方法 'PUT', 'POST', 'PATCH'
  33. 键值对,会将请求体转换成json格式
  34. },
  35. data:'name=jeff&age=18', 会将请求体转换成url参数形式,即表单形式
  36. withCredentials: false, 跨域请求时是否需要使用凭证
  37. adapter: function (config) { 请求适配器设置,如前台发送ajaxnodejs中发送http请求
  38. 返回一个 promise 并应用一个有效的响应
  39. },
  40. auth: { 使用HTTP基础验证,并提供凭据这将设置一个`Authorization` 头,覆写掉现有的任意使用`headers`设置的自定义`Authorization`
  41. username: 'janedoe',
  42. password: 's00pers3cret'
  43. },
  44. responseType: 'json', 服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  45. responseEncoding: 'utf8', 表示解码响应时使用的编码
  46. 服务器返回结果时会返回唯一的标识,下次发送请求得传递标识,检测成功才会相应,避免响应其他客户端发送的请求
  47. xsrfCookieName: 'XSRF-TOKEN', 跨域请求cookie的标识
  48. xsrfHeaderName: 'X-XSRF-TOKEN', 跨域头信息设置
  49. onUploadProgress: function (progressEvent) { 上传处理进度事件
  50. ...
  51. },
  52. onDownloadProgress: function (progressEvent) { 下载处理进度事件
  53. ...
  54. },
  55. maxContentLength: 2000, 允许的响应内容的最大尺寸
  56. maxRedirects: 5, 定义在node.jsfollow的最大重定向数目
  57. validateStatus: function (status) { 定义对于给定的HTTP响应状态码是resolvereject promise,如果 `validateStatus` 返回 `true` (或者设置为 `null` `undefined`),promise将被resolve; 否则,promise将被rejecte
  58. return status >= 200 && status < 300; // default
  59. },
  60. socketPath: null, 定义在node.js中使用的UNIX Socket的路径位置,如果使用了proxy代理,优先使用socketPath;
  61. httpAgent: new http.Agent({ keepAlive: true }),`httpAgent` `httpsAgent` 分别在 node.js 中用于定义在执行httphttps时使用的自定义代理,允许像这样配置选项:
  62. httpsAgent: new https.Agent({ keepAlive: true }),
  63. 这将会设置一个`Proxy-Authorization`头,覆写掉已有的通过使用`header`设置的自定义 `Proxy-Authorization` 头。
  64. proxy: { 'proxy' 定义代理服务器的主机名称和端口
  65. host: '127.0.0.1',
  66. port: 9000,
  67. auth: { `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
  68. username: 'mikeymike',
  69. password: 'rapunz3l'
  70. }
  71. },
  72. cancelToken: new CancelToken(function (cancel) {
  73. 取消axios请求的配置
  74. })
  75. })
  76. 4.5axios全局配置:
  77. 全局axios配置:
  78. 所有的请求都会生效
  79. axios.defaults.属性='xxxx'
  80. 自定义实例配置:
  81. const instance = axios.create({
  82. baseURL: 'https://api.example.com'
  83. });
  84. instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
  85. 5axios实例
  86. 可用于创建不同域名的请求
  87. const instance=axios.create({
  88. 配置
  89. })
  90. 使用: 使用方式和axios的两种方式相同
  91. instance({url:'',...}).then((res)=>{...})
  92. instance.get('url',{...}).then(res=>{...})
  93. 6、在组件函数中使用
  94. (1)get请求:
  95. axios.get("url",{配置})
  96. .then(res=>{ res.data获取数据})
  97. .catch(err=>{console.log(err)})//错误捕捉
  98. (2)get请求传参:
  99. 方式一:在url后拼接参数
  100. 方式二:
  101. axios.get('url',{params:{
  102. 键值对
  103. }
  104. }).then(res=>res.data)
  105. .catch(err=>console.log(err))
  106. axios({
  107. method:'get',
  108. url:'x',
  109. params:{
  110. 键值对
  111. }
  112. }).then(res=>res.data)
  113. (3)post请求
  114. 1、若被拦截,引入qs
  115. import qs from 'qs' post的参数转换成url?键值对的形式,否则会被拦截
  116. 因为post中的键值对会以对象形式添加
  117. 2、创建请求
  118. axios.post(url,data参数,{配置})
  119. axios.post('url',qs.stringify({
  120. 键值对
  121. }),{配置}).then(res=>{res.data}).catch(err=>console.log(err))
  122. axios({
  123. method:'post',
  124. url:'x',
  125. data:{...}或字符串格式
  126. })
  127. (4)当后台返回了状态码时
  128. axios.get('url').then(
  129. ()=>{},
  130. ({response})=>{response.data} 获取错误情况下数据
  131. )
  132. (5)并行请求
  133. axios.all([axios请求1,axios请求2]).then((res)=>{
  134. 数组
  135. res[0]/...
  136. })
  137. axios.all([axios请求1,axios请求2]).then(
  138. axios.spread((res1,res2)=>{
  139. ...
  140. })
  141. )
  142. (6)axios返回流式内容(前端axios无法使用,import引入的,后端axios才行)
  143. (1)node_modules中找到axios
  144. (2)将lib/adapters/http.js中的内容全选复制到lib/adapters/xhr.js
  145. axios({method:'get',url,responseType:'stream'}).then(res=>{
  146. res.data.pipe(fs.createWriteStream('C:/Users/10853/Desktop/'+title+".epub"))
  147. })
  148. 案例:通过流读取下载电子书
  149. axios({method:'get',url,responseType:'stream'}).then(res=>{
  150. res.data.pipe(fs.createWriteStream('C:/Users/10853/Desktop/'+title+".epub"))
  151. res.data.on('end',function(){
  152. console.log('下载完毕');
  153. })
  154. })
  155. (7)axios拦截器
  156. 拦截器中的两个方法参数和Promise的.then的方法参数效果相同
  157. 多个请求拦截器:后面的会先执行,因为两个方法参数是被unshift插入执行的集合中
  158. 多个响应拦截器:前面的会先执行,因为两个方法参数是被push进入执行的集合中
  159. (1)添加请求拦截器
  160. axios.interceptors.request.use(function (config) {
  161. 在发送请求之前做些什么,configaxios的配置对象
  162. config.headers.Authorization=token
  163. return config;
  164. }, function (error) { 会接收请求拦截器中抛出的错误
  165. 对请求错误做些什么
  166. return Promise.reject(error);
  167. });
  168. (2)添加响应拦截器
  169. axios.interceptors.response.use(function (response) {
  170. 对响应数据做点什么,responseaxios的返回结果对象
  171. return response;
  172. }, function (error) {
  173. 对响应错误做点什么
  174. return Promise.reject(error);
  175. });
  176. (8)取消请求
  177. const CancelToken = axios.CancelToken;
  178. const source = CancelToken.source();
  179. axios.get('/rl', {
  180. cancelToken: source.token 方式一:
  181. cancelToken:new CancelToken((c)=>{
  182. 变量=c;
  183. })
  184. }).catch(err=>{
  185. if (err.message == "interrupt") {
  186. console.log('已中断请求');
  187. return;
  188. }
  189. })
  190. 方式一中断请求:source.cancel('interrupt');
  191. 方式二中断请求:变量('interrupt');
  192. (9)多个请求只发送一次,利用取消请求的特性
  193. 将取消请求的函数赋值给一个变量,当数据返回时将变量修改为null,每次请求判断变量是否为null,不是则取消
  194. const CancelToken = axios.CancelToken;
  195. let cont=null;
  196. if(cont!==null){
  197. cont();
  198. }
  199. axios.get('/rl', {
  200. cancelToken: source.token 方式一:
  201. cancelToken:new CancelToken((c)=>{
  202. cont=c;
  203. })
  204. }).then(()=>{
  205. cont=null;
  206. })

代码示例;
main.js:

  1. import Vue from 'vue'
  2. import App from './App'
  3. import Axios from 'axios'
  4. Vue.config.productionTip = false
  5. Vue.prototype.$axios=Axios
  6. /* eslint-disable no-new */
  7. new Vue({
  8. el: '#app',
  9. data:{ foo:'hello foo'},
  10. components: { App },
  11. template: '<App/>'
  12. })

组件:

  1. <template>
  2. <div>
  3. </div>
  4. </template>
  5. <script>
  6. import qs from 'qs'
  7. export default{
  8. name:'d',
  9. data()
  10. {
  11. return{
  12. }
  13. },
  14. mounted()
  15. {
  16. this.$axios.get("http://localhost:3000/news")
  17. .then(res=>{
  18. console.log(res.data);
  19. })
  20. .catch(err=>{
  21. console.log(err)
  22. })
  23. this.$axios.post("http://localhost:3000/movie",qs.stringify({ id:2})).then(res=>console.log(res.data)).catch(err=>console.log(err))
  24. }
  25. }
  26. </script>
  27. <style lang="css">
  28. </style>

发表评论

表情:
评论列表 (有 0 条评论,777人围观)

还没有评论,来说两句吧...

相关阅读

    相关 axios网络请求

    > 人的一生就像一篇文章,只有经过多次精心修改,才能不断完善。 > 你好,我是梦阳辰,期待与你相遇! 文章目录 01.概述 02.axios请求方式