axios学习笔记

axios安装

npm install axios --save

axios基本使用方式

axios(config)

<script>
	//基本使用:axios默认使用**get**请求
	axios({
		url: 'http://localhost:8080/student',
	}).then(res => {
		//res为响应成功数据
		//响应成功处理
		console.log(res);
	}).catch(err => {
		//err为响应失败数据
		//响应失败处理
		console.log(err);
	})
</script>

get请求带参形式

//例如
<script>
	//url带参
	axios({
		url: 'http://localhost:8080/student?id=1',
	}).then(res => {
		console.log(res);
	}).catch(err => {
		console.log(err);
	})
</script>
	//params传参
<script>
	axios({
		url: 'http://localhost:8080/student',
		params: {
			id:1
		}
	}).then(res => {
		console.log(res);
	}).catch(err => {
		console.log(err);
	})
</script>

get请求简写方式

	//无参
<script>
	axios.get('http://localhost:8080/student').then(res =>
		console.log(res);
	).catch(err => {
		console.log(err);
	})
</script>
	//有参
<script>
	axios.get('http://localhost:8080/student',{params:{id:1}}).then(res =>
		console.log(res);
	).catch(err => {
		console.log(err);
	})
</script>

以method属性指定请求方式,以post为例(简写看下面)

注意:
params:是添加到url的请求字符串中的,用于get请求
data:是添加到请求体(body)中的,用于post请求

<script>
	axios({
		url: 'http://localhost:8080/student',
		method: 'post',
		data: {
			id: 1  //出现问题,后端无法接收到数据 id=null 原因:data方式默认发送的是application/json格式数据
		}
	}).then(res => {
		console.log(res);
	})
</script>

上述问题解决方式
① 前端-将传参形式改为params

<script>
	axios({
		url: 'http://localhost:8080/student',
		method: 'post',
		//也是以拼接url方式传参:http://localhost:8080/student?id=1 实测解决了问题 后端接收到了数据
		//明文 不推荐使用
		params: {
			id: 1 
		}
	}).then(res => {
		console.log(res);
	})
</script>

② 后端-方法形参前加上@RequestBody注解接收参数

@RequestMapping("/student")
public Student getStudentById(@RequestBody Integer id){
	...
}

③ Content-Type改为application/x-www-form-urlencoded
在main.js文件中添加:

import axios from 'axios';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

post请求简写方式

//无参
<script>
	axios.post('http://localhost:8080/student').then(res =>
		console.log(res);
	).catch(err => {
		console.log(err);
	})
</script>
//第一种:有参 后端无需处理
<script>
	//不可使用{params:{id: 1}}方式传递
	//原因:默认使用application/json方式传参
	axios.post('http://localhost:8080/student',"id=1").then(res => //多个参数时,这样写"id=1&name=zhangsan"
		console.log(res);
	).catch(err => {
		console.log(err);
	})
</script>
//第二种:有参 后端需使用@RequestBody
<script>
	//该方式本质上使用data:{}方式传递,后端方法需使用@RequestBody注解接收参数 且传过来的是一个对象 后端需要使用对象接收
	axios.post('http://localhost:8080/student',{id: 1}).then(res => //多个参数时,这样写"id=1&name=zhangsan"
		console.log(res);
	).catch(err => {
		console.log(err);
	})
</script>

axios并发请求

axios.all()

axios.all([请求1,请求2]);

<script>
	axios.all([
	axios.get("http://localhost:8080/student/getAllStudent"),
	axios.get("http://localhost:8080/student/getStudentById",{params:{id:1}})
	]).then(res => {
		console.log(res);//返回的是一个数组 包含两个请求的结果
	}).catch(err => {
		console.log(err);
	})
</script>

因为响应成功,返回的是一个包含两个请求结果的数组,可通过以下方式拿到:

console.log(res[0]);
console.log(res[1]);

axios.spread()

但是过于繁琐 axios提供了axios.spread()方法分割响应结果:

<script>
	axios.all([
	axios.get("http://localhost:8080/student/getAllStudent"),
	axios.get("http://localhost:8080/student/getStudentById",{params:{id:1}})
	]).then(
		axios.spread((res1,res2) => {
			console.log(res1);
			console.log(res2);
		})
	).catch(err => {
		console.log(err);
	})
</script>

axios 全局配置

在main.js中

	axios.default.baseURL = "http://localhost:8080/项目名";//配置完成后 url自动拼接
	axios.default.timeout = 5000;//设置请求超时时间为5s

axios 实例创建与使用(局部配置)

<script>
	//创建
	let axiosInstance = axios.create({
		baseURL: "http://localhost:8080/...";
		timeout: 5000;
	});
	//使用
	//形式:axiosInstance(config)
	axiosInstance({
		url:"/student/getStudentAll"
	}).then(res => {
		console.log(res);
	}).catch(err => {
		console.log(err);
	})
</script>

axios 拦截器

axios提供两大类拦截器:

  1. 1.请求拦截:
    1.1成功请求拦截
    1.2失败请求拦截
  2. 2.响应拦截
    2.1响应成功拦截
    2.2响应失败拦截

使用场景:
① 发起请求时添加网页加载动画
② 验证token 强制登陆
③ 数据过滤
④ 响应数据处理
⑤ 根据响应状态码跳转页面:例如跳转至错误页面

axios 请求拦截

格式:axios.interceptor.xx.use(success => {},faild => {});

//全局拦截
	axios.interceptor.request.use(success=>{
		//这里写成功请求处理代码
		return success;//这里一定要返回成功请求信息,否则会报错 请求不能继续
	},faild=>{
		//这里写失败请求处理代码
	});

axios 响应拦截

//全局拦截
	axios.interceptor.resoonse.use(success=>{
		//这里写成功请求处理代码
		console.log(success);
		//这里一定要返回,否则返回结果为undefined 请求拿不到数据
		//return success;
		//但是我们一般只需要返回数据即可
		return success.data;
	},faild=>{
		//这里写失败请求处理代码
	});

axios在vue中的模块封装

创建src/network/request.js

import axios from 'axios'
export function request(config){
	//创建一个实例
	let axiosInstance = axios.create({
		baseURL: "http://localhost:8080/...",
		timeout: 5000;
	});
	//axios.create()创建的就是一个AxiosPromise对象
	return axiosInstance(config);
}

调用

<script>
	import {request} form "src/network/request"
	request({
		url:"/getStudentById",
		data:{
			id: 1
		},
		method: 'post'
	}).then(res => {
		console.log(res);
	}).catch(err => {
		console.log(err);
	})
</script>

附录:全部配置选项

链接: 参考资料.

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

  // `method` 是创建请求时使用的方法
  method: 'get', // 默认是 get

  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  baseURL: 'https://some-domain.com/api/',

  // `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` 序列化的函数
  // (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 专属: Stream
  data: {
    firstName: 'Fred'
  },

  // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
  // 如果请求话费了超过 `timeout` 的时间,请求将被中断
  timeout: 1000,

  // `withCredentials` 表示跨域请求时是否需要使用凭证
  withCredentials: false, // 默认的

  // `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', // 默认的

  // `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 < 300; // 默认的
  },

  // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
  // 如果设置为0,将不会 follow 任何重定向
  maxRedirects: 5, // 默认的

  // `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) {
  })
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值