axios的get post传参与springboot的接受参数总结

前后端参数传递详解:GET、POST、PUT、DELETE 请求

在现代 Web 开发中,前后端分离架构非常普遍。为了实现前后端的有效通信,我们需要掌握不同 HTTP 方法(GET、POST、PUT、DELETE)下的参数传递方式。本文将详细介绍这些方法,并提供具体的前端和后端代码示例。

1. GET 请求

1.1 通过 params 选项传递查询参数

这是最常见的方式,适用于大多数场景。

前端代码示例

 

javascript

深色版本

import { ref } from 'vue';
import axios from 'axios';

const params1 = ref({ id: 1, name: 'John' });

axios.get('/api/category',  params1)
  .then(response => {
    console.log('响应数据:', response.data);
  })
  .catch(error => {
    console.error('错误:', error);
  });

Spring Boot 后端接收

 

java

深色版本

@RestController
@RequestMapping("/api")
public class CategoryController {

  @GetMapping("/category")
  public ResponseEntity<String> getCategory(
      @RequestParam("id") Integer id,
      @RequestParam("name") String name) {
    String response = "收到的 id: " + id + ", 名称: " + name;
    return ResponseEntity.ok(response);
  }
}

1.2 直接在 URL 中拼接参数

适用于简单的参数传递。

前端代码示例

 

javascript

深色版本

import { ref } from 'vue';
import axios from 'axios';

const params1 = ref({ id: 1, name: 'John' });

axios.get(`/api/category?id=${params1.value.id}&name=${encodeURIComponent(params1.value.name)}`)
  .then(response => {
    console.log('响应数据:', response.data);
  })
  .catch(error => {
    console.error('错误:', error);
  });

Spring Boot 后端接收

 

java

深色版本

@RestController
@RequestMapping("/api")
public class CategoryController {

  @GetMapping("/category")
  public ResponseEntity<String> getCategory(
      @RequestParam("id") Integer id,
      @RequestParam("name") String name) {
    String response = "收到的 id: " + id + ", 名称: " + name;
    return ResponseEntity.ok(response);
  }
}

1.3 使用 URLSearchParams 传递查询参数

适用于需要动态构建查询参数的场景。

前端代码示例

 

javascript

深色版本

import { ref } from 'vue';
import axios from 'axios';

const params = new URLSearchParams();
params.append('id', 555);

axios.get('/api/category/del', { params })
  .then(response => {
    console.log('响应数据:', response.data);
  })
  .catch(error => {
    console.error('错误:', error);
  });

Spring Boot 后端接收

 

java

深色版本

@RestController
@RequestMapping("/api/category")
public class CategoryController {

  @RequestMapping("/del")
  public ResponseEntity<String> del(@RequestParam("id") Integer id) {
    String response = "收到的 id: " + id;
    return ResponseEntity.ok(response);
  }
}

2. POST 请求

2.1 通过请求体传递 JSON 数据

这是最常见的 POST 请求方式,适用于传递复杂对象。

前端代码示例

 

javascript

深色版本

import { ref } from 'vue';
import axios from 'axios';

const params1 = ref({ id: 1, name: 'John' });

axios.post('/api/category', params1.value)
  .then(response => {
    console.log('响应数据:', response.data);
  })
  .catch(error => {
    console.error('错误:', error);
  });

Spring Boot 后端接收

 

java

深色版本

@RestController
@RequestMapping("/api")
public class CategoryController {

  @PostMapping("/category")
  public ResponseEntity<String> createCategory(@RequestBody CategoryRequest request) {
    String response = "收到的 id: " + request.getId() + ", 名称: " + request.getName();
    return ResponseEntity.ok(response);
  }

  @Data
  public static class CategoryRequest {
    private Integer id;
    private String name;
  }
}

2.2 通过 URLSearchParams 传递表单数据

适用于发送表单数据(application/x-www-form-urlencoded 格式)。

前端代码示例

 

javascript

深色版本

import { ref } from 'vue';
import axios from 'axios';

const params1 = ref({ id: 1, name: 'John' });

const params = new URLSearchParams(params1.value);

axios.post('/api/category', params, {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
  .then(response => {
    console.log('响应数据:', response.data);
  })
  .catch(error => {
    console.error('错误:', error);
  });

Spring Boot 后端接收

 

java

深色版本

@RestController
@RequestMapping("/api")
public class CategoryController {

  @PostMapping("/category")
  public ResponseEntity<String> createCategory(
      @RequestParam("id") Integer id,
      @RequestParam("name") String name) {
    String response = "收到的 id: " + id + ", 名称: " + name;
    return ResponseEntity.ok(response);
  }
}

3. PUT 请求

3.1 通过请求体传递 JSON 数据

PUT 请求一般用于更新资源,所以可以明确指出这种请求的语义和 RESTful 设计中,如何将更新操作和 PUT 请求映射。

前端代码示例

 

javascript

深色版本

import { ref } from 'vue';
import axios from 'axios';

const params1 = ref({ id: 1, name: 'John Updated' });

axios.put('/api/category', params1.value)
  .then(response => {
    console.log('响应数据:', response.data);
  })
  .catch(error => {
    console.error('错误:', error);
  });

Spring Boot 后端接收

 

java

深色版本

@RestController
@RequestMapping("/api")
public class CategoryController {

  @PutMapping("/category")
  public ResponseEntity<String> updateCategory(@RequestBody CategoryRequest request) {
    String response = "更新的 id: " + request.getId() + ", 名称: " + request.getName();
    return ResponseEntity.ok(response);
  }

  @Data
  public static class CategoryRequest {
    private Integer id;
    private String name;
  }
}

4. DELETE 请求

4.1 使用 params 选项传递查询参数

在 RESTful 风格 API 设计中,/api/category/{id} 可以更明确地代表删除特定 ID 资源。如果有可能传递多个查询参数(如分页或过滤条件),可以在 DELETE 请求中通过 { params: params } 方式,确保服务端按需删除资源。

前端代码示例

 

javascript

深色版本

import { ref } from 'vue';
import axios from 'axios';

const params1 = ref({ id: 1 });

axios.delete('/api/category', { params: params1.value })
  .then(response => {
    console.log('响应数据:', response.data);
  })
  .catch(error => {
    console.error('错误:', error);
  });

Spring Boot 后端接收

 

java

深色版本

@RestController
@RequestMapping("/api")
public class CategoryController {

  @DeleteMapping("/category")
  public ResponseEntity<String> deleteCategory(@RequestParam("id") Integer id) {
    String response = "删除的 id: " + id;
    return ResponseEntity.ok(response);
  }
}

4.2 直接在 URL 中拼接参数

在 RESTful 风格 API 设计中,/api/category/{id} 可以更明确地代表删除特定 ID 资源。

前端代码示例

 

javascript

深色版本

import { ref } from 'vue';
import axios from 'axios';

const params1 = ref({ id: 1 });

axios.delete(`/api/category/${params1.value.id}`)
  .then(response => {
    console.log('响应数据:', response.data);
  })
  .catch(error => {
    console.error('错误:', error);
  });

Spring Boot 后端接收

 

java

深色版本

@RestController
@RequestMapping("/api")
public class CategoryController {

  @DeleteMapping("/category/{id}")
  public ResponseEntity<String> deleteCategory(@PathVariable("id") Integer id) {
    String response = "删除的 id: " + id;
    return ResponseEntity.ok(response);
  }
}

总结

  • GET 请求:查询数据,适合用于获取资源信息。

    • 使用 params 选项:前端 axios.get(url, { params: params }),后端 @RequestParam
    • URL 拼接参数:前端手动拼接,后端 @RequestParam 或 @PathVariable
  • POST 请求:创建资源,用于发送较为复杂的对象。

    • JSON 数据:前端 axios.post(url, data),后端 @RequestBody
    • 表单数据:前端 application/x-www-form-urlencoded 格式,后端 @RequestParam 或 @ModelAttribute
  • PUT 请求:更新资源。

    • JSON 数据:前端 axios.put(url, data),后端 @RequestBody
  • DELETE 请求:删除资源。

    • 查询参数:前端 axios.delete(url, { params: params }),后端 @RequestParam
    • URL 拼接:前端拼接 ID,后端 @PathVariable

优化建议

  • HTTP 规范中的传参方式适用场景:在每个请求方法的总结中都提及 HTTP 规范中的传参方式适用场景(如 GET 请求适用于查询,POST 用于创建,PUT 用于更新,DELETE 用于删除),增强可读性和逻辑性。
  • DELETE 请求的直接拼接 URL:后端部分最好使用 @PathVariable,这是 RESTful API 中的最佳实践。
  • 示例代码调整建议:如果需要在多个地方进行参数拼接,可以将 axios 请求封装成通用方法,进一步简化代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值