【axios】get/post請求params/data傳參總結

axios中get/post請求方式

1. 前言

最近突然發現post請求可以使用params方式傳值,然後想總結一下其中的用法。

2.1 分類

在這裏插入圖片描述
get請求中沒有data傳值方式

2.2 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();
}

使用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相似,基礎類型接收,名字對應即可

// 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. 總結

總體來說,只要使用 params get與post請求基本是一樣使用的,如果參數名與傳遞名稱不一致,需要使用@RequestParam修飾,若使用Map接收參數,必須使用@RequestParam修飾。但是如果想傳list類型的數據,需要使用單獨的方法處理(參考鏈接)。
若使用data傳遞參數,必須使用一個實體類接收參數,而且需要添加註解@RequestBody進行修飾。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章