axios

axios概述

Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。

Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node.js 中。

Github开源地址: https://github.com/axios/axios

使用

在线地址引入

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

npm安装

 npm install axios

GET请求

axios.defaults.baseURL = 'http://192.168.43.35:8000'
// 第一种get请求传参  ?参数
axios.get('/product?ID=933')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

//第二种get请求传参 params

axios.get('/product', {
params: {
ID: 933
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})

POST请求

axios.defaults.baseURL = 'http://192.168.43.35:8000'
axios.post('/cont', {
    uid: 1578,
    cid: 984
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

可以通过将相关配置传递给 axios 来进行请求

// axios.defaults  配置默认请求结构
axios.defaults.baseURL = 'http://192.168.43.35:8000'
//在所有请求时就不需要加 http://192.168.43.35:8000  直接写后面路径就可以了

const config = {
  method: 'get',  //请求方式
  url: '/product',
  data: {
    ID:933
  },
  //请求头信息
  headers: {
        // 'X-Requested-With': 'XMLHttpRequest',
        // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        'content-type': 'application/json;charset=UTF-8'
      }
}

axios(config)

配置详解 这里引用了官方的文档说明

{
  // `url`是将用于请求的服务器URL
  url: '/user',

  // `method`是发出请求时使用的请求方法

  // `baseURL`将被添加到`url`前面,除非`url`是绝对的。
  // 可以方便地为 axios 的实例设置`baseURL`,以便将相对 URL 传递给该实例的方法。
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest`允许在请求数据发送到服务器之前对其进行更改
  // 这只适用于请求方法'PUT','POST'和'PATCH'

  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: {
    et: 'sss'
  },

  // `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) {
  })
}

并发

axios.all([
    axios.post('/procudt',{id:933}),
    axios.get('/facs',{parms:{id:1}})
])
.then(
    axios.spread((res1,res2)=>{
       //响应所有结果
        console.log(res1)
        console.log(res2)
    })
)
.catch(error=>{
    console.log(error)
})

创建实例

var instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});
instance({
  method:'get'
  url:'/scok'
}).than(res=>{
  console.log(res)
})

拦截器

在这里插入图片描述

// 添加请求拦截器
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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值