≡
  • 网络编程
  • 数据库
  • CMS技巧
  • 软件编程
  • PHP笔记
  • JavaScript
  • MySQL
位置:首页 > 网络编程 > vue.js

Vue 中axios配置实例分析

人气:750 时间:2019-04-11

这篇文章主要为大家详细介绍了Vue 中axios配置实例分析,具有一定的参考价值,可以用来参考一下。

感兴趣的小伙伴,下面一起跟随四海网的小编两巴掌来看看吧!

 

1.GET 请求

 

代码如下:


//向具有指定ID的用户发出请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 也可以通过 params 对象传递参数
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

 

2.POST请求

 

代码如下:


axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

 

3执行多个并发请求

 

代码如下:


function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
//两个请求现已完成
}));

 

4.请求配置

 

这些是用于发出请求的可用配置选项。 只有url是必需的。 如果未指定方法,请求将默认为GET.

代码如下:


{  // `url`是将用于请求的服务器URL
  url: '/user',
  // `method`是发出请求时使用的请求方法
  method: 'get', // 默认
  // `baseURL`将被添加到`url`前面,除非`url`是绝对的。
  // 可以方便地为 axios 的实例设置`baseURL`,以便将相对 URL 传递给该实例的方法。
  baseURL: 'https://some-domain.com/api/',
  // `transformRequest`允许在请求数据发送到服务器之前对其进行更改
  // 这只适用于请求方法'PUT','POST'和'PATCH'
  // 数组中的最后一个函数必须返回一个字符串,一个 ArrayBuffer或一个 Stream
  transformRequest: [function (data) {
  // 做任何你想要的数据转换
  return data;
  }],
  // `transformResponse`允许在 then / catch之前对响应数据进行更改
  transformResponse: [function (data) {
  // Do whatever you want to transform the data
  return data;
  }],
  // `headers`是要发送的自定义 headers
  headers: {'X-Requested-With': 'XMLHttpRequest'},
  // `params`是要与请求一起发送的URL参数
  // 必须是纯对象或URLSearchParams对象
  params: {
  ID: 12345
  },
  // `paramsSerializer`是一个可选的函数,负责序列化`params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
  return Qs.stringify(params, {arrayFormat: 'brackets'})
  },
  // `data`是要作为请求主体发送的数据
  // 仅适用于请求方法“PUT”,“POST”和“PATCH”
  // 当没有设置`transformRequest`时,必须是以下类型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser only: FormData, File, Blob
  // - Node only: Stream
  data: {
  firstName: 'Fred'
  },
  // `timeout`指定请求超时之前的毫秒数。
  // 如果请求的时间超过'timeout',请求将被中止。
  timeout: 1000,
  // `withCredentials`指示是否跨站点访问控制请求
  // should be made using credentials
  withCredentials: false, // default
  // `adapter'允许自定义处理请求,这使得测试更容易。
  // 返回一个promise并提供一个有效的响应(参见[response docs](#response-api))
  adapter: function (config) {
  /* ... */
  },
  // `auth'表示应该使用 HTTP 基本认证,并提供凭据。
  // 这将设置一个`Authorization'头,覆盖任何现有的`Authorization'自定义头,使用`headers`设置。
  auth: {
  username: 'janedoe',
  password: 's00pers3cret'
  },
  // “responseType”表示服务器将响应的数据类型
  // 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default
  //`xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名称
  xsrfCookieName: 'XSRF-TOKEN', // default
  // `xsrfHeaderName`是携带xsrf令牌值的http头的名称
  xsrfHeaderName: 'X-XSRF-TOKEN', // default
  // `onUploadProgress`允许处理上传的进度事件
  onUploadProgress: function (progressEvent) {
  // 使用本地 progress 事件做任何你想要做的
  },
  // `onDownloadProgress`允许处理下载的进度事件
  onDownloadProgress: function (progressEvent) {
  // Do whatever you want with the native progress event
  },
  // `maxContentLength`定义允许的http响应内容的最大大小
  maxContentLength: 2000,
  // `validateStatus`定义是否解析或拒绝给定的promise
  // HTTP响应状态码。如果`validateStatus`返回`true`(或被设置为`null` promise将被解析;否则,promise将被
   // 拒绝。
  validateStatus: function (status) {
  return status >= 200 && status < 300; // default
  },
  // `maxRedirects`定义在node.js中要遵循的重定向的最大数量。
  // 如果设置为0,则不会遵循重定向。
  maxRedirects: 5, // 默认
  // `httpAgent`和`httpsAgent`用于定义在node.js中分别执行http和https请求时使用的自定义代理。
  // 允许配置类似`keepAlive`的选项,
  // 默认情况下不启用。
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),
  // 'proxy'定义代理服务器的主机名和端口
  // `auth`表示HTTP Basic auth应该用于连接到代理,并提供credentials。
  // 这将设置一个`Proxy-Authorization` header,覆盖任何使用`headers`设置的现有的`Proxy-Authorization` 自定义 headers。
  proxy: {
  host: '127.0.0.1',
  port: 9000,
  auth: : {
  username: 'mikeymike',
  password: 'rapunz3l'
  }
  },
  // “cancelToken”指定可用于取消请求的取消令牌
  // (see Cancellation section below for details)
  cancelToken: new CancelToken(function (cancel) {
  })
 }

 

5.全局axios默认值

 

代码如下:


 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';

 

6.拦截器

 

你可以截取请求或响应在被 then 或者 catch 处理之前

代码如下:


//添加请求拦截器<==>请求发起前做的事
axios.interceptors.request.use(function(config){
   //在发送请求之前做某事
   return config;
  },function(error){
   //请求错误时做些事
   return Promise.reject(error);
  });
//添加响应拦截器<==>响应回来后做的事
axios.interceptors.response.use(function(response){
   //对响应数据做些事
   return response;
  },function(error){
   //请求错误时做些事
   return Promise.reject(error);
  });

   如果你以后可能需要删除拦截器。、

代码如下:


 var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
  axios.interceptors.request.eject(myInterceptor);

    你可以将拦截器添加到axios的自定义实例

代码如下:


  var instance = axios.create();
  instance.interceptors.request.use(function () {/*...*/});

 

总结

 

以上所述是小编给大家介绍的Vue 中axios配置实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对四海网网站的支持!

本文来自:http://www.q1010.com/184/5969-0.html

注:关于Vue 中axios配置实例分析的内容就先介绍到这里,更多相关文章的可以留意四海网的其他信息。

关键词:vue.js

您可能感兴趣的文章

  • mpvue小程序仿qq左滑置顶删除组件
  • vue修改对象的属性值后页面不重新渲染的实例
  • vue devtools的安装与使用教程
  • 分析vuex中mutation/action的传参方式
  • vue+element-ui集成随机验证码+用户名+密码的form表单验证功能
  • 分析vue axios用post提交的数据格式
  • 分析如何在vue-cli中使用vuex
  • vue2.0的虚拟DOM渲染思路分析
  • vue.js提交按钮时进行简单的if判断表达式分析
  • 分析Vue开发微信H5微信分享签名失败问题解决方案
上一篇:Vue三种常用传值示例(父传子、子传父、非父子)
下一篇:解决vue this.$forceUpdate() 处理页面刷新问题(v-for循环值刷新等)
热门文章
  • Vue 报错TypeError: this.$set is not a function 的解决方法
  • vue实现动态添加数据滚动条自动滚动到底部的示例代码
  • vue项目设置scrollTop不起作用(总结)
  • vue项目中使用vue-i18n报错的解决方法
  • iview实现select tree树形下拉框的示例代码
  • 分析关于element级联选择器数据回显问题
  • vue项目打包后打开页面空白解决办法
  • 解决element ui select下拉框不回显数据问题的解决
  • element-ui table span-method(行合并)的实现代码
  • element-ui 设置菜单栏展开的方法
  • 最新文章
    • 理解vue ssr原理并自己搭建简单的ssr框架
    • vue favicon设置以及动态修改favicon的方法
    • vue-router启用history模式下的开发及非根目录部署方法
    • 从零开始在NPM上发布一个Vue组件的方法步骤
    • Element input树型下拉框的实现代码
    • Vue 报错TypeError: this.$set is not a function 的解决方法
    • Vue.js组件高级特性实例分析
    • 浅谈VueJS SSR 后端绘制内存泄漏的相关解决经验
    • 分析Vue.js自定义tipOnce指令用法实例
    • 浅谈vuex actions和mutation的异曲同工

四海网收集整理一些常用的php代码,JS代码,数据库mysql等技术文章。