axios POST提交数据的三种请求方式写法

imgAwbeci发布于 2018-06-12

img

1、Content-Type: application/json

import axios from 'axios'
let data = {"code":"1234","name":"yyyy"};
axios.post(`${this.$url}/test/testRequest`,data)
.then(res=>{
    console.log('res=>',res);            
})

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LgLZ1eEe-1639275244253)(https://segmentfault.com/img/bVbccg7?w=854&h=362)]

2、Content-Type: multipart/form-data

import axios from 'axios'
let data = new FormData();
data.append('code','1234');
data.append('name','yyyy');
axios.post(`${this.$url}/test/testRequest`,data)
.then(res=>{
    console.log('res=>',res);            
})

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oiFK2PDf-1639275244254)(https://segmentfault.com/img/bVbcchv?w=1820&h=686)]

3、Content-Type: application/x-www-form-urlencoded

import axios from 'axios'
import qs from 'Qs'
let data = {"code":"1234","name":"yyyy"};
axios.post(`${this.$url}/test/testRequest`,qs.stringify({
    data
}))
.then(res=>{
    console.log('res=>',res);            
})

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0vGh0rTO-1639275244258)(https://segmentfault.com/img/bVbccih?w=1822&h=368)]

总结:
1、从jquery转到axios最难忘的就是要设置Content-Type,还好现在都搞懂了他们的原理
2、上面三种方式会对应后台的请求方式,这个也要注意,比如java的@RequestBody,HttpSevletRequest等等

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐