axios的使用

axios是基于Promise的HTTP库,适用于各种前端框架。

不同于普通http请求后的回调,Promise有更好的操作性。
axios可以自动转换JSON数据
客户端支持防御XSRF攻击

axios的简单使用

安装

npm install axios --save

执行get请求

   axios.get("http://localhost:8080/user?id=1").then(response => {
      console.log(response );
    }).catch(error => {
      console.log(error);
    })

也可以将请求的参数用另一种表达方式

	axios.get("http://localhost:8080/user", {params: {id = 1}}).then(response => {
      	console.log(response );
   	 }).catch(error => {
      	console.log(error);
   	 })

执行post请求

	axios.post("http://localhost:8080/user", {username: "name"},opt).then(response => {
  		console.log(response);
	}).catch(error => {
  		console.log(error);
	})

执行put请求

axios.put("http://localhost:8080/user", {username: "name"},opt).then(response => {
  console.log(response);
}).catch(error => {
  console.log(error);
});

执行delete请求

axios.delete("http://localhost:8080/user",{params:{id}}).then(response => {
  console.log(response);
}).catch(error => {
  console.log(error);
});

在post请求和put请求中,会有后台获取不到数据的情况,主要的原因有:

  • 请求的的Content-Type 为application/json格式
  • axios会自动将数据转换为json
    在这里插入图片描述
    我使用的Java后台服务希望得到的是Content-Type: application/x-www-form-urlencoded请求,很明显这样是使用@RequestParam是获取不到参数的

有几种解决方法
第一种
使用axios中自带的Qs来包裹请求的参数,添加了axios模块,Qs直接引入就可以使用

import Qs from 'qs';
axios.post("http://localhost:8080/user",Qs.stringify({username: "name"}),opt).then(response => {
	console.log(response);
}).catch(error => {
	console.log(error);
})

这样就能正常的获取到参数,content-type变为application/x-www-urlencoded

第二种
使用URLSearchParams

const param = new URLSearchParams();
param.append('username', 'name')
axios.post(url, data).then(response => {
  console.log(response);
}).catch(error => {
  console.log(error);
})

第三种
在Java服务中,获取参数的方式采用@RequestBody注解

axios api

可以通过向axios传递相关的配置参数创建请求

axios(config)
config: {
	//用于请求的服务器 URL
	url,
	//创建请求时使用的方法
	method,
	//将自动加在 `url` 前面,除非 `url` 是一个绝对 URL
	baseURL,
	//允许在向服务器发送前,修改请求数据
	//只能用在post,put,patch请求方法
	transformRequest,
	//在传递给 then/catch 前,允许修改响应数据
	transformResponse,
	//允许自定义请求头
	headers,
	//与请求一起发送的URL参数
	params,
	//将params序列化的函数
	paramsSerializer,
	//作为请求体发送的数据
	data,
	//指定超时的毫秒数
	timeout,
	//表示跨域请求时是否需要使用凭证,默认false
	withCredentials,
	//允许自定义处理请求
	adapter,
	//应该使用 HTTP 基础验证,并提供凭据
	auth,
	//服务器响应的数据类型,默认'json'
	responseType,
	//xsrf token 的值的cookie的名称
	xsrfCookieName,
	//xsrf token 的值的http头的名称
	xsrfHeaderName,
	//允许为上传处理进度事件
	onUploadProgress,
	//允许为下载处理进度事件
	onDownloadProgress,
	//定义允许的响应内容的最大尺寸
	maxContentLength,
	//定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise,默认status >= 200 && status < 300;
	validateStatus,
	//定义在 node.js 中 follow 的最大重定向数目。设置为0,将不会 follow 任何重定向
	maxRedirects,
	//定义在执行 http 和 https 时使用的自定义代理,`keepAlive` 默认false
	httpAgent,
	httpsAgent,
	//代理服务器的主机名称和端口
	proxy:{
	host: '127.0.0.1',
	port: 9000
	},
	//指定用于取消请求的 cancel token
	cancelToken
}

响应结构

{
  //由服务器提供的响应
  data: {},
  //来自服务器响应的 HTTP 状态码
  status: 200,
  //来自服务器响应的 HTTP 状态信息
  statusText: 'OK',
  // 服务器响应的头
  headers: {},
  // 是为请求提供的配置信息
  config: {}
}

配置默认值
可以通过defaults来配置全局axios的默认配置

axios.defaults.baseURL='http://localhost'

创建自定义实例

    var server = axios.create({
    	baseURL:'http://localhost'
    })
 	server.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

拦截器

// 添加请求拦截器
axios.interceptors.request.use(config => {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(response => {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });
  //自定义axios实例添加拦截器
  var server = axios.create()
  server.interceptors.request.use(config => {})

参考:
https://www.kancloud.cn/yunye/axios/234845
https://blog.csdn.net/csdn_yudong/article/details/79668655#1_25

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值