23.axios传参特点
传参风格
1.GET 和 POST 的“待遇”不同,Axios 的设计者给这两个方法定义的参数规则不一样:
2.axios.post(url, data, config)
第 2 个参数默认就是给你放数据(Body)的,所以你可以直接传 userInfo,不需要包一层。
后端接受参数
@PostMapping("/user/add")
// ✅ 必须加 @RequestBody,否则收不到 JSON
public String addUser(@RequestBody User user) {
return "收到 JSON:" + user.getName();
}
3.axios.get(url, config)
-
第 2 个参数是“配置项”(Config),它没有专门放数据的位置。如果你想传数据,必须把数据塞到配置项的一个叫 params 的口袋里。
//这种不符合 REST 风格,会拼接参数 const uerInfo = { name: 'ylf', age: 19, address: 'guizhou' }; axios.get('http://localhost:8089/springmvc_redis_war/user/add', { params:uerInfo }).then(res=>{ console.log("后端返回的数据为"+res.data) }).catch(err=>{ console.log(err.msg) }) //即最终的url http://localhost:8089/springmvc_redis_war/user/add?name=ylf&age=19&address=guizhou那么spring后端怎样接受参数呢?
第一种接受参数的方法:Spring 会自动匹配(只要对象的属性名和 URL 里的参数名一样)。@GetMapping("/add") // @RequestBody 的作用:把前端传来的 JSON 自动转成上面的 UserInfo 对象 @ResponseBody // 注意:这里千万不要加 @RequestBody!如果不加注解,Spring 默认就是从 URL 找参数封装进对象 public String saveUser(UserInfo userInfo) { System.out.println("================"); System.out.println("后端成功收到数据:" + userInfo); System.out.println("================"); return userInfo.toString() +"get"; }第二种接受参数的方法:直接使用参数对照
@RequestMapping("/user/get") // 注意:这里不需要 @RequestBody! // Spring 会自动把 URL 里的 name 赋值给这里的 name 变量 public String getUser(String name, Integer age,String address) { return "收到:" + name + ", " + age +"," + address; } -
那么如果我想要使用REST风格传递参数呢,使用模板字符串拼接url吧
const userId = 1001; // 使用反引号,${变量名} axios.get(`http://localhost:8089/springmvc_redis_war/user/add/${userId}`); // 结果 URL: http://localhost:8089/springmvc_redis_war/user/add/1001那么spring后端怎样接受参数呢?
第一种接受参数的方法
@GetMapping("/user/{id}") // 这里的 ("id") 是为了告诉 Spring 把路径里的 {id} 赋值给参数 id public String getUserById(@PathVariable("id") Integer id) { ... }第二种接受参数的方法:简写写法(推荐), 如果你的Java 方法参数名(Integer id)和URL 里的占位符(
{id})名字完全一样,那么括号里的内容可以省略!@GetMapping("/user/{id}") // ✅ 只要名字对得上,("id") 可以不写 public String getUserById(@PathVariable Integer id) { return "ID: " + id; }

浙公网安备 33010602011771号