AXIOS 入门
01-Axios 简介
Axios (Ai ke C U S , ajax i/o system),Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中;客户端向服务器端发送异步请求。Vue 官方提倡使用 Axios 来操作 AJAX 异步请求。
官网地址:axios中文网|axios API 中文文档 | axios

特点:
- 支持浏览器和 node.js
- 能拦截请求和响应
- 能转换请求和响应数据
- 能取消请求
- 自动转换 JSON 数据
- 浏览器端支持防止 CSRF (跨站请求伪造)
1.1 项目添加 axios
1)下载
// 浏览器直接访问下载地址然后保存https://unpkg.com/axios/dist/axios.min.js
2)然后把下载的文件放在自己的项目中,然后在需要使用的页面引入
<script src="static/vue/axios.min.js"></script>
02-发送AJAX请求
2.1 Get请求
1)语法
axios.get(url [, cong] );
axios.get('user/list').then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});
2)传参
[1] 路径传参
axios.get("goods/list?pageNum="+this.p.pageNum+"&pageSize="+this.p.pageSize).then(function (response){this.vm.page=response.data;}).catch(function (error) {//alert("获取数据失败");})
[2] params 传参
axios.get("brand/list",{params:{cateId:this.goodssign.cateId,}}).then(function (response) {this.vm.listthreesign=response.data;}).catch(function (ee) {alert("品牌加载失败");})
2.2 Post 请求
1)语法
axios.post(url[, data[, cong]]);
axios.post('user/list').then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});
2)传参
[1] 名 - 值对,自己拼接
axios.post("goods/delete","id="+id).then(function (response) {console.log(response);location.reload();}).catch(function (ed) {alert("删除失败");})
[2] 当参数已经封装 js 对象,可以使用 qs.js 转化
axios.post("goods/list",Qs.stringify(this.pagetwo)).then(function (response) {this.vm.page=response.data;}).catch(function (error) {alert("页面加载失败");})
导入 qs
<script src="js/qs.js"></script>
注意: qs 进行 js 对象转化为 “名-值对”,只适合于 js 对象结构简单(简单 js 对象)如果 js 对象结构复杂,不适合使用 qs 将 js 对象转化为名值对,进行参数传递。复杂参数结构:应该直接传递参数,json 对象。
[3] json 对象传参(常用)
axios.post("goods/update",this.goodssign).then(function (response) {console.log(response);location.reload();}).catch(function (ee) {alert("修改失败");})
2.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) {// 两个请求现在都执行完成}));
03-创建实例
3.1 自定义新建 axios 实例
const instance = axios.create({baseURL: 'https://some-domain.com/api/',timeout: 1000,headers: {'X-Custom-Header': 'foobar'}});
3.2 配置项
{// `url` 是用于请求的服务器 URLurl: '/user',// `method` 是创建请求时使用的方法method: 'get', // default// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URLbaseURL: 'https://some-domain.com/api/',// `transformRequest` 允许在向服务器发送前,修改请求数据// 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法// 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 StreamtransformRequest: [function (data, headers) {// 对 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` 序列化的函数// (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// - 浏览器专属:FormData, File, Blob// - Node 专属: Streamdata: {firstName: 'Fred'},// `timeout` 指定请求超时的毫秒数(0 表示无超时时间)// 如果请求话费了超过 `timeout` 的时间,请求将被中断timeout: 1000,// `withCredentials` 表示跨域请求时是否需要使用凭证withCredentials: false, // default// `adapter` 允许自定义处理请求,以使测试更轻松// 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).adapter: function (config) {/* ... */},// `auth` 表示应该使用 HTTP 基础验证,并提供凭据// 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头auth: {username: 'janedoe',password: 's00pers3cret'},// `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'responseType: 'json', // default// `responseEncoding` indicates encoding to use for decoding responses// Note: Ignored for `responseType` of 'stream' or client-side requestsresponseEncoding: 'utf8', // default// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称xsrfCookieName: 'XSRF-TOKEN', // default// `xsrfHeaderName` is the name of the http header that carries the xsrf token valuexsrfHeaderName: 'X-XSRF-TOKEN', // default// `onUploadProgress` 允许为上传处理进度事件onUploadProgress: function (progressEvent) {// Do whatever you want with the native progress event},// `onDownloadProgress` 允许为下载处理进度事件onDownloadProgress: function (progressEvent) {// 对原生进度事件的处理},// `maxContentLength` 定义允许的响应内容的最大尺寸maxContentLength: 2000,// `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejectevalidateStatus: function (status) {return status >= 200 && status < 300; // default},// `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目// 如果设置为0,将不会 follow 任何重定向maxRedirects: 5, // default// `socketPath` defines a UNIX Socket to be used in node.js.// e.g. '/var/run/docker.sock' to send requests to the docker daemon.// Only either `socketPath` or `proxy` can be specified.// If both are specified, `socketPath` is used.socketPath: null, // default// `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:// `keepAlive` 默认没有启用httpAgent: new http.Agent({ keepAlive: true }),httpsAgent: new https.Agent({ keepAlive: true }),// 'proxy' 定义代理服务器的主机名称和端口// `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据// 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。proxy: {host: '127.0.0.1',port: 9000,auth: {username: 'mikeymike',password: 'rapunz3l'}},// `cancelToken` 指定用于取消请求的 cancel token// (查看后面的 Cancellation 这节了解更多)cancelToken: new CancelToken(function (cancel) {})}
04-拦截器
在请求或响应被 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);});
05-经验总结
5.1 接收参数问题
1)@RestController
如果一个 Controller 类中都是 ajax 处理方法,没必要所有方法加 @ResponseBody,为了简化开发可以使用 @RestController。该注解相当于 @Controller + @ResponseBody@RestController@RequestMapping("/axios2")public class AxiosController2 {}
2)@GetMapping 和 @PostMapping
@GetMapping("/hello") 相当于 @RequestMapping(value = "/hello",method = RequestMethod.GET)@PostMapping("/test02") 相当于 @RequestMapping(value="/test02",method = RequestMethod.POST)
3)@RequestBody 和 @RequestParam
@RequestParam 抓取参数,只能抓取-名值对 (application/x-www-formurlencoded)@RequestBody 抓取参数,抓取是json对象(xml 对象)(application/json)
4)@RequestBody 和 @ResponseBody
@RequestBody:请求有关 请求参数是 json 对象, 将请求 json 对象整体接收----> 封装 java 对象@ResponseBody:响应有关 将返回数据整体作为响应结果。如果返回 java 对象----》转化为 json 格式字符串@ResponseBody 代表方法是 ajax 处理
5.2 js 中 this 问题
this 问题:在 vue 实例中的 this 代表的是 vue 实例,而在 axios 请求中 this 代表的是 window ,要在 axios 请求中获取 this 需要 this.vue 参数名。
var app = new Vue({el:"#app",data:{},methods:{loginSubmit(){instance.get("/admin/sysUser/verifyCode").then(function (response) {var data = response.data;if(data.success){console.log(this.app)}else{alert(data.message);}}).catch(function (error) {console.log(error);alert("系统内部错误!");})}}})
注意:如果使用 ES6 的匿名函数特性就不会有 this 问题。
06-qs.js
第三方,方便 json 对象 和 字符串(名-值对格式)进行转化工具。基本不怎么使用,初学使用。qs.js 只适用于简单的对象信息,复杂的对象信息解析会出错。
6.1 使用步骤
1)导入
<script src="js/qs.js"></script>
2)使用方法
var string = Qs.stringify(简单js对象);
