欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Vue 中axios配置实例详解

程序员文章站 2022-03-20 15:25:38
1.get 请求 //向具有指定id的用户发出请求 axios.get('/user?id=12345') .then(function (respo...

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配置实例详解,希望对大家有所帮助