关于axios的相关操作

axios的使用

1.axios的特征

​ 1.axios是基于promise的用于浏览器和node.js的HTTP客户端

​ 2.从浏览器中创建XMLHttpRequest

​ 3.从node.js发出http请求

​ 4.拦截(拦截器) 请求和响应

​ 5.转换请求和响应数据

​ 6.取消请求

​ 7.自动转换JSON数据

​ 8.客户端支持防止CSRF/XSRF攻击

​ 9.支持promiseAPI

2.一些常用的初始化配置

axios.defaults.baseURL = 'https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp';
// 默认的路由

axios.interceptors.response.use(result => result.data);
//=>设置响应拦截器:分别在响应成功和失败的时候做一些拦截处理(在执行成功后设定的方法之前,先会执行拦截器中的方法)

axios.defaults.validateStatus = function validateStatus(status) {
 //=>自定义成功失败规则:RESOLVE / REJECT(默认规则:状态码以2开头算作成功)
      return /^(2|3)d{2}$/.test(status);
};

 //=>设置在POST请求中基于请求主体向服务器发送内容的格式,默认是RAW,项目中常用的是URL-ENCODEED格式
axios.defaults.headers['Content-Type'] = 'appliction/x-www-form-urlencoded';

axios.defaults.transformRequest = data => {
    //=>DATA:就是请求主体中需要传递给服务器的内容(对象)
    let str = ``;
    for (let attr in data) {
        if (data.hasOwnProperty(attr)) {
            str += `${attr}=${data[attr]}&`;
        }
    }
    return str.substring(0, str.length - 1);
};

3.一些使用方法

1.get/post请求的使用
// 写法一
this.axios({
	url: "",  // 提交的路由
	data: {},  // post请求提交的数据
	params: {},  // get请求提交的数据
	methods: "",  // 请求方式
}).then(function(response) {
	// 执行成功后执行的回调函数
}).catch(function(response) {
	// 当then方法抛异常时触发
})


// 写法二:直接点出axios中的请求类型的方法
// get请求
axios.get('url',{
	data: {},  // post请求提交的数据
	params: {},  // get请求提交的数据,显示在url上
}).then(function(res){
  console.log(res);//处理成功的函数 相当于success
}).catch(function(error){
  console.log(error)// 打印then函数抛的异常
})

// post请求
axios.post('url',{
	data: {},  // post请求提交的数据
	params: {},  // get请求提交的数据,显示在url上
}).then(function(res){
  console.log(res);//处理成功的函数 相当于success
}).catch(function(error){
  console.log(error)//打印then函数抛的异常
})

补充:其它的请求方法(了解)
axios.get(url {数据,配置})
axios.delete(url {数据,配置})
axios.head(url {数据,配置})
axios.post(url {数据,配置})
axios.put(url {数据,配置})
axios.patch(url {数据,配置})
// 当使用别名方法时,不需要在config中指定url,method和data属性
请求中的配置
1. `url`是将用于请求的服务器URL
url: ‘/user’,
2. `method`是发出请求时使用的请求方法
method: ‘get’, // 默认
3. `baseURL`将被添加到`url`前面,除非`url`是绝对的。
// 可以方便地为 axios 的实例设置`baseURL`,以便将相对 URL 传递给该实例的方法。
baseURL: ‘https://some-domain.com/api/’, 
4. `transformRequest`允许在请求数据发送到服务器之前对其进行更改
// 这只适用于请求方法’PUT’,’POST’和’PATCH’
// 数组中的最后一个函数必须返回一个字符串,一个 ArrayBuffer或一个 Stream 
transformRequest: [function (data) {
// 做任何你想要的数据转换 然后  return data;
}], 
5. `transformResponse`允许在 then / catch之前对响应数据进行更改
transformResponse: [function (data) {
  // 做任何你想要的数据转换 然后  return data;
}], 
6. `headers`是要发送的自定义 headers
headers: {‘X-Requested-With’: ’XMLHttpRequest’},
7. `params`是要与请求一起发送的URL参数
// 必须是纯对象或URLSearchParams对象
params: {
  ID: 12345
}, 
8.  `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’})
}, 
9. `data`是要作为请求主体发送的数据
// 仅适用于请求方法“PUT”,“POST”和“PATCH”
// 当没有设置`transformRequest`时,必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream
data: {
  firstName: ’Fred’
}, 
10. `timeout`指定请求超时之前的毫秒数。
// 如果请求的时间超过’timeout’,请求将被中止。
timeout: 1000,
11.  `withCredentials`指示是否跨站点访问控制请求
withCredentials: false, // default
12.  `adapter’允许自定义处理请求,这使得测试更容易。
// 返回一个promise并提供一个有效的响应(参见[response docs](#response-api))
adapter: function (config) {
/* … */
}, 
13.  `auth’表示应该使用 HTTP 基本认证,并提供凭据。
// 这将设置一个`Authorization’头,覆盖任何现有的`Authorization’自定义头,使用`headers`设置。
auth: {
  username: ’janedoe’,
  password: ’s00pers3cret’
}, 
14.  “responseType”表示服务器将响应的数据类型
// 包括 ‘arraybuffer’, ‘blob’, ‘document’, ‘json’, ‘text’, ‘stream’
responseType: ‘json’, // default 
15. `xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名称
xsrfCookieName: ‘XSRF-TOKEN’, // default 
16.  `xsrfHeaderName`是携带xsrf令牌值的http头的名称
xsrfHeaderName: ‘X-XSRF-TOKEN’, // default 
17.  `onUploadProgress`允许处理上传的进度事件
onUploadProgress: function (progressEvent) {
// 使用本地 progress 事件做任何你想要做的
}, 
18.  `onDownloadProgress`允许处理下载的进度事件
onDownloadProgress: function (progressEvent) {
}, 
19.  `maxContentLength`定义允许的http响应内容的最大大小
maxContentLength: 2000, 
20.  `validateStatus`定义是否解析或拒绝给定的promise
// HTTP响应状态码。如果`validateStatus`返回`true`(或被设置为`null` promise将被解析;否则,promise将被
  // 拒绝。
validateStatus: function (status) {
  return status >= 200 && status < 300; // default
}, 
21.  `maxRedirects`定义在node.js中要遵循的重定向的最大数量。
// 如果设置为0,则不会遵循重定向。
maxRedirects: 5, // 默认 
22.  `httpAgent`和`httpsAgent`用于定义在node.js中分别执行http和https请求时使用的自定义代理。
// 允许配置类似`keepAlive`的选项,
// 默认情况下不启用。
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }), 
23.  ‘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’
  }
}, 
24.  “cancelToken”指定可用于取消请求的取消令牌
cancelToken: new CancelToken(function (cancel) {
})
}
2.axios的并发的实现
let axiosList = [
	this.axios({}),
	this.axios({})
]

this.axios.all(axiosList).then(axios.spread(function(response1, response2) {
	// response1, response2分别为两个并发执行的axios的回调函数的返回值
})).catch(axios.spread(function(response1, response2) {
	// response1, response2分别为两个并发执行的axios的回调函数then抛的异常
}))
// axios是基于promise实现功能的,而promise是一种解决异步编程的方法.想要实现axios并发可以先将每个axios事件放在列表中,通过axios内部的all方法实现多个axios事件的并发执行.

关于配置 方法的一些写法(仅供参考):

export default {
        name: "Test",
        data() {
            return {
                input: '',
                msg: '',
            }
        },
        methods: {
            submitA() {
                if (this.input) {
                    //     // 回调函数不能直接使用组件中data中的定义的数据.换句话说回调函数获取的值不能赋值给组件中的data的值
                    //     // 原因是axios中的this是指代的是Vue,可以在执行axios之前用一个变量缓存Vue,
                    //     // 例如定义一个变量,将Vue指代的this赋值给该变量,在其它地方就可以使用该变量代替this
                    let that = this;
                    // this.$axios({
                    //     url: 'http://127.0.0.1:8000/test/',
                    //     methods: "get",
                    //     // params: {
                    //     //     input_a: this.input,
                    //     // },  // get请求的数据放在request.GET中
                    //     data: {
                    //         input_a: this.input,
                    //     },  // post请求后端取不到error
                    // }).then(function (response) {
                    //     // 回调函数不能直接使用组件中data中的定义的数据.换句话说回调函数获取的值不能赋值给组件中的data的值
                    //     // 原因是axios中的this是指代的是Vue,可以在执行axios之前用一个变量缓存Vue,
                    //     // 例如定义一个变量,将Vue指代的this赋值给该变量,在其它地方就可以使用该变量代替this
                    //     that.msg = response.data.msg;
                    // }).catch(function (error) {
                    //     console.log(error)  // 打印then函数抛的异常
                    // })
                    this.$axios.get(
                        "http://127.0.0.1:8000/test/",
                        {
                            params: {input_a: that.input},
                            headers:{'Content-Type': 'appliction/x-www-form-urlencoded'},
                            responseType: 'json',
                        }
                    ).then(function (response) {
                        that.msg = response.data.msg
                    }).catch(function (response) {
                        that.msg = response.data.msg
                    });
                }
            }
        }
    }
原文地址:https://www.cnblogs.com/le-le666/p/11728224.html