Axios概述
首先,axios是基于promise用于浏览器和node.js的http客户端
特点 :
支持浏览器和node.js
支持promise
能拦截请求和响应
能转换请求和响应数据
能取消请求
自动转换json数据
浏览器端支持防止CSRF(跨站请求伪造)
一、 安装
npm安装
$ npm install axios
bower安装
$ bower install axios
通过cdn引入
1 |
首先需要安装axios
下一步,在main.js中引入axios
1 | import axios from "axios" ; |
与很多第三方模块不同的是,axios不能使用use方法,由于axios比vue出来的早 所以需要放到vue的原型对象中
1 | Vue.prototype.$axios = axios; |
接着,我们就可以在App.vue中使用axios了
1 2 3 4 5 | created: function (){ this .$axios.get( "/seller" ,{ "id" :123}).then(res=>{ console.log(res.data); }); } |
1.发起一个get请求
1 2 3 4 5 6 7 8 9 10 11 | <input id= "get01Id" type= "button" value= "get01" ><script> $( "#get01Id" ).click( function () { .then( function (value) { console.log(value); }) . catch ( function (reason) { console.log(reason); }) }) </script> |
另外一种形式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <input id= "get02Id" type= "button" value= "get02" ><script> $( "#get02Id" ).click( function () { params: { id: 1 } }) .then( function (value) { console.log(value); }) . catch ( function (reason) { console.log(reason); }) }) </script> |
2.发起一个post请求
在官方文档上面是这样的:
1 2 3 4 5 6 7 8 | axios.post( '/user' , { firstName: 'Fred' , lastName: 'Flintstone' }).then( function (res) { console.log(res); }). catch ( function (err) { console.log(err); }); |
但是如果这么写,会导致后端接收不到数据
所以当我们使用post请求的时候,传递参数要这么写:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <input id= "post01Id" type= "button" value= "post01" ><script> $( "#post01Id" ).click( function () { var params = new URLSearchParams(); params.append( 'username' , 'sertyu' ); params.append( 'password' , 'dfghjd' ); .then( function (value) { console.log(value); }) . catch ( function (reason) { console.log(reason); }); }) </script> |
3.执行多个并发请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <input id= "button01Id" type= "button" value= "点01" ><script> function getUser1() { } function getUser2() { } $( "#buttonId" ).click( function () { axios.all([getUser1(), getUser2()]) .then(axios.spread( function (user1, user2) { alert(user1.data.username); alert(user2.data.username); })) }) </script> |
另外一种形式:
1 2 3 4 5 6 7 8 9 10 11 12 | <input id= "button02Id" type= "button" value= "点02" ><script> $( "#button02Id" ).click( function () { axios.all([ ]) .then(axios.spread( function (user1, user2) { alert(user1.data.username); alert(user2.data.username); })) }) </script> |
当所有的请求都完成后,会收到一个数组,包含着响应对象,其中的顺序和请求发送的顺序相同,可以使用axios.spread分割成多个单独的响应对象
三、 axiosAPI
(一)可以通过向axios传递相关配置来创建请求
axios(config)
1 2 3 4 5 6 7 8 9 10 11 12 13 | <input id= "buttonId" type= "button" value= "点" ><script> $( "#buttonId" ).click( function () { var params = new URLSearchParams(); params.append( 'username' , 'trewwe' ); params.append( 'password' , 'wertyu' ); // 发起一个post请求 axios({ method: 'post' , data:params }); }) </script> |
axios(url[,config])
1 2 3 4 5 6 | <input id= "buttonId" type= "button" value= "点" ><script> $( "#buttonId" ).click( function () { // 发起一个get请求,(get是默认的请求方法) }) </script> |
(二)请求方法别名
axios.request(config)
axios.get(url[, config])
axios.delete(url[,config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])在使用别名方法时,url、method、data这些属性都不必在配置中指定
(三)并发请求,即是帮助处理并发请求的辅助函数
1 2 3 4 | //iterable是一个可以迭代的参数如数组等 axios.all(iterable) //callback要等到所有请求都完成才会执行 axios.spread(callback) |
(四)创建实例,使用自定义配置
1.axios.create([config])
1 2 3 4 5 | var instance = axios.create({ timeout:1000, headers: { 'X-Custom-Header' : 'foobar' } }); |
2.实例的方法
以下是实例方法,注意已经定义的配置将和利用create创建的实例的配置合并
axios#request(config)
axios#get(url[,config])
axios#delete(url[,config])
axios#head(url[,config])
axios#post(url[,data[,config]])
axios#put(url[,data[,config]])
axios#patch(url[,data[,config]])
四、请求配置
请求的配置选项,只有url选项是必须的,如果method选项未定义,那么它默认是以get方式发出请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | { // url 是用于请求的服务器 URL url: '/user/getWord' , // method 是创建请求时使用的方法 method: 'get' , // 默认是 get // baseURL 将自动加在 url 前面,除非 url 是一个绝对路径。 // 它可以通过设置一个 baseURL 便于为 axios 实例的方法传递相对路径 // transformRequest 允许在向服务器发送前,修改请求数据 // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法 // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream transformRequest: [ function (data) { // 对 data 进行任意转换处理 return data; }], // transformResponse 在传递给 then/catch 前,允许修改响应数据 transformResponse: [ function (data) { // 对 data 进行任意转换处理 return data; }], // headers 是即将被发送的自定义请求头 headers: { 'X-Requested-With' : 'XMLHttpRequest' }, // params 是即将与请求一起发送的 URL 参数 // 必须是一个无格式对象(plain object)或 URLSearchParams 对象 params: { ID: 12345 }, // paramsSerializer 是一个负责 params 序列化的函数 paramsSerializer: function (params) { return Qs.stringify(params, {arrayFormat: 'brackets' }) }, // data 是作为请求主体被发送的数据 // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH' // 在没有设置 transformRequest 时,必须是以下类型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - 浏览器专属:FormData, File, Blob // - Node 专属: Stream data: { firstName: 'yuyao' }, // timeout 指定请求超时的毫秒数(0 表示无超时时间) // 如果请求话费了超过 timeout 的时间,请求将被中断 timeout: 1000, // withCredentials 表示跨域请求时是否需要使用凭证 withCredentials: false , // 默认的 // adapter 允许自定义处理请求,以使测试更轻松 // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)). adapter: function (config) { /* ... */ }, // auth 表示应该使用 HTTP 基础验证,并提供凭据 // 这将设置一个 Authorization 头,覆写掉现有的任意使用 headers 设置的自定义 Authorization 头 auth: { username: 'zhangsan' , password: '12345' }, // responseType 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json' , // 默认的 // xsrfCookieName 是用作 xsrf token 的值的cookie的名称 xsrfCookieName: 'XSRF-TOKEN' , // default // xsrfHeaderName 是承载 xsrf token 的值的 HTTP 头的名称 xsrfHeaderName: 'X-XSRF-TOKEN' , // 默认的 // onUploadProgress 允许为上传处理进度事件 onUploadProgress: function (progressEvent) { // 对原生进度事件的处理 }, // onDownloadProgress 允许为下载处理进度事件 onDownloadProgress: function (progressEvent) { // 对原生进度事件的处理 }, // maxContentLength 定义允许的响应内容的最大尺寸 maxContentLength: 2000, // validateStatus 定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。 // 如果 validateStatus 返回 true (或者设置为 null 或 undefined ),promise 将被 resolve; 否则,promise 将被 rejecte validateStatus: function (status) { return status >= 200 && status |
五、响应内容
1 2 3 4 5 6 7 8 9 10 | { data:{}, status:200, //从服务器返回的http状态文本 statusText: 'OK' , //响应头信息 headers: {}, //config是在请求的时候的一些配置信息 config: {} } |
可以这样来获取响应信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <input id= "getId" type= "button" value= "get" ><script> $( "#getId" ).click( function () { .then( function (value) { console.log( "data:" +value.data); console.log( "status:" +value.status); console.log( "statusText:" +value.statusText); console.log( "headers:" +value.headers); console.log( "config:" +value.config); }) . catch ( function (reason) { console.log(reason); }) }) </script> |
六、默认配置
默认配置对所有请求都有效
1、全局默认配置
1 2 3 | axios.defaults.headers.common[ 'Authorization' ] = AUTH_TOKEN; axios.defaults.headers.post[ 'content-Type' ] = 'appliction/x-www-form-urlencoded' ; |
2、自定义的实例默认设置
1 2 3 4 5 6 | //当创建实例的时候配置默认配置 var instance = axios.create({ }); //当实例创建时候修改配置 instance.defaults.headers.common[ "Authorization" ] = AUTH_TOKEN; |
3、配置中有优先级
config配置将会以优先级别来合并,顺序是lib/defauts.js中的默认配置,然后是实例中的默认配置,最后是请求中的config参数的配置,越往后等级越高,后面的会覆盖前面的例子。
1 2 3 4 5 6 7 8 9 10 | //创建一个实例的时候会使用libray目录中的默认配置 //在这里timeout配置的值为0,来自于libray的默认值 var instance = axios.create(); //回覆盖掉library的默认值 //现在所有的请求都要等2.5S之后才会发出 instance.defaults.timeout = 2500; //这里的timeout回覆盖之前的2.5S变成5s instance.get( '/longRequest' ,{ timeout: 5000 }); |
七、拦截器
1.可以在请求、响应在到达then/catch之前拦截
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //添加一个请求拦截器 axios.interceptors.request.use( function (config){ //在请求发出之前进行一些操作 return config; }, function (err){ //Do something with request error return Promise.reject(error); }); //添加一个响应拦截器 axios.interceptors.response.use( function (res){ //在这里对返回的数据进行处理 return res; }, function (err){ //Do something with response error return Promise.reject(error); }) |
2.取消拦截器
1 2 | var myInterceptor = axios.interceptor.request.use( function (){ /*....*/ }); axios.interceptors.request.eject(myInterceptor); |
3.给自定义的axios实例添加拦截器
1 2 | var instance = axios.create(); instance.interceptors.request.use( function (){}) |
八、错误处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <input id= "getId" type= "button" value= "get" ><script> $( "#getId" ).click( function () { . catch ( function (error) { if (error.response) { //请求已经发出,但是服务器响应返回的状态吗不在2xx的范围内 console.log( "data:" +error.response.data); console.log( "status:" +error.response.status); console.log( "header:" +error.response.header); } else { //一些错误是在设置请求的时候触发 console.log( 'Error' , error.message); } console.log(error.config); }); }) </script> |
九、取消
通过一个cancel token来取消一个请求
通过CancelToken.source工厂函数来创建一个cancel token
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <input id= "getId" type= "button" value= "get" ><input id= "unGetId" type= "button" value= "unGet" ><script> var CancelToken = axios.CancelToken; var source = CancelToken.source(); $( "#getId" ).click( function () { cancelToken: source.token }) .then( function (value) { console.log(value); }) . catch ( function (thrown) { if (axios.isCancel(thrown)) { console.log( 'Request canceled' , thrown.message); } else { //handle error } }); }); $( "#unGetId" ).click( function () { //取消请求(信息的参数可以设置的) source.cancel( "操作被用户取消" ); }); </script> |
到此这篇关于axios get post请求 传递参数的文章就介绍到这了,更多相关axios get post请求 传递参数内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!