axios的请求方式
1、get请求
params参数 基础接收,需要参数名对应
// method
const params = {
id: '123456789',
name: '张三'
}
test(params)
// api
export function test (params) {
return axios({
url: url,
method: 'GET',
params: params
})
}
// 后台
@GetMapping("/test")
public Result test(Long id, String name) {
return Res.ok();
}
params参数 使用map接收,需要使用RequestParam 注解
// method
const params = {
id: '123456789',
name: '张三'
}
test(params)
// api
export function test (params) {
return axios({
url: url,
method: 'GET',
params: params
})
}
// 后台
@GetMapping("/test")
public Result test(@RequestParam Map<String, Object> map) {
return Res.ok();
}
params参数 使用实体类接收
// 实体类
@Data
public class TestEntity {
Long id;
String name;
}
// method
const params = {
id: '123456789',
name: '张三'
}
test(params)
// api
export function test (params) {
return axios({
url: url,
method: 'GET',
params: params
})
}
// 后台
@GetMapping("/test")
public Result test(TestEntity testEntity) {
return Res.ok();
}
2、post请求
使用params传参 与 get方式相同
使用data传参
// 实体类
@Data
public class TestEntity {
Long id;
String name;
}
// method
const params = {
id: '123456789',
name: '张三'
}
test(params)
// api
export function test (params) {
return axios({
url: url,
method: 'POST',
data: params
})
}
@PostMapping("/test")
public Result test(@RequestBody TestEntity testEntity) {
return Res.ok();
}
post请求时遇到的那些坑
请求头设置为
{
headers: {'Content-Type':'application/x-www-form-urlencoded'}
}
传参形式
export const updatePreventionStrategy = (data) => {
return axios({
url: 'test/updateTest',
method: 'post',
data: data
})
}
遇到的问题(在浏览器中看传参的类型不正确):
解决方案:
import qs from 'qs'
export const updatePreventionStrategy = (data) => {
return axios({
url: 'test/updateTest',
method: 'post',
data: qs.stringify(data)
})
}
总结:因为这里我用axios处理的 contentType
为 application/x-www-form-urlencoded
而且后端是用 @RequestParam
来接收前端传过来的参数的,所以post传参的时候用的是 qs.stringify(data)
,若后台使用 @RequestBody
,则应该使用 JSON.stringify(data)
来转化格式。其导致这个坑的最主要原因就是后端中 @RequestParam
和@RequestBody
的差别所致.
参考地址1:https://blog.csdn.net/xiao_bai_9527/article/details/106950219
参考地址2:https://blog.csdn.net/banmingi/article/details/99604412