axios中g(shù)et/post請求方式
1. 前言
最近突然發(fā)現(xiàn)post請求可以使用params方式傳值,然后想總結(jié)一下其中的用法挚歧。
2.1 分類
經(jīng)過查閱資料愤诱,get請求是可以通過body傳輸數(shù)據(jù)的,但是許多工具類并不支持此功能丑瞧。
在postman中甫恩,選擇get請求后逆济,body選項自動變?yōu)榱嘶疑?br> 即,不建議使用此方式傳輸數(shù)據(jù)。
2.2 get請求
params
基礎(chǔ)類型接收奖慌,名字對應(yīng)即可
// 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();
}
使用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();
}
使用實體類接收
// 實體類
@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();
}
ps: get請求不允許傳遞List,需要使用qs插件
或者配置axios
简僧,具體參考鏈接
2.3 post請求
2.3.1 params 與 get方式相同
與get相似建椰,基礎(chǔ)類型接收,名字對應(yīng)即可
// method
const params = {
id: '123456789',
name: '張三'
}
test(params)
// api
export function test (params) {
return axios({
url: url,
method: 'POST',
params: params
})
}
// 后臺
@PostMapping("/test")
public Result test(Long id, String name) {
return Res.ok();
}
與get相似涎劈,使用map接收
// method
const params = {
id: '123456789',
name: '張三'
}
test(params)
// api
export function test (params) {
return axios({
url: url,
method: 'POST',
params: params
})
}
// 后臺
@PostMapping("/test")
public Result test(@RequestParam Map<String, Object> map) {
return Res.ok();
}
與get相似广凸,使用實體類接收
// 實體類
@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',
params: params
})
}
// 后臺
@PostMapping("/test")
public Result test(TestEntity testEntity) {
return Res.ok();
}
2.3.2 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();
}
4. 總結(jié)
總體來說,只要使用 params
get與post請求基本是一樣使用的蛛枚,如果參數(shù)名與傳遞名稱不一致谅海,需要使用@RequestParam
修飾,若使用Map接收參數(shù)蹦浦,必須使用@RequestParam
修飾扭吁。但是如果想傳list
類型的數(shù)據(jù),需要使用單獨的方法處理(參考鏈接)盲镶。<br />若使用data
傳遞參數(shù)侥袜,必須使用一個實體類接收參數(shù),而且需要添加注解@RequestBody
進行修飾溉贿。