微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用vue插件axios传数据的Content-Type及格式问题详解

1.一般来说,前后台对接,常用的Content-Type有:

application/json,application/x-www-form-urlencoded 以及 multipart/form-data,当我们使用axios时,一般不需要我们主动去设置Content-Type,而是跟着我们传的数据格式自动适应。

2.get请求

get请求时传递的参数是会出现在url里面的,我们使用aixos传递get请求时可用格式如下
(1)将参数拼接在url里

this.$axios({
	method: 'get',url: this.$store.state.api1 
		+ '&username=' + 'xxx' 
		+ '&password=' + 'xxx'
})

(2)将参数放入params对象里

this.$axios({
	method: 'get',url: this.$store.state.api1,params: {
		username: 'xxx',password: 'xxx'
	}
})

3.post请求

(1)当我们要传对象时,此时的 Content-Type 为 application/json 类型,传递的格式如下,将传递的参数放入对象中:

this.$axios({
	url: this.$store.state.api1,method: 'post',data: {
		username: 'xxx',password: 'xxx'
	}
})

(2)当我们要传字符串时,Content-Type 为 application/x-www-form-urlencoded 类型,传递的格式有如下:

this.$axios({
	method: 'post',data: 'username=' + 'xxx'
		+ '&password=' + 'xxx'
	})
this.$axios({
method: 'post',data: qs.stringify({
	username: 'xxx',password: 'xxx'
})

(3)当我们要传文件时,Content-Type 需要使用 multipart/form-data,格式如下:

// 获取文件
let input = document.querySelector('.input_file')
let curFiles = input.files

// 将文件放入formData中
let formData = new FormData()
for(let file of curFiles){
	formData.append('files',file)
}

// 将需要传递的参数放入formData中
formData.append('username','xxx')
formData.append('password','xxx')

// 调接口
this.$axios({
	url: this.$store.state.api1,data: formData
})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐