前端后端交互请求的几种方式

以下是常见的请求方式及其使用例子:

常见的请求方式有以下几种:

1. GET:获取资源,请求参数在URL中传递,一般用于数据查询操作。
2. POST:提交数据,请求参数在请求体中传递,一般用于数据新增和修改操作。
3. PUT:更新数据,请求参数在请求体中传递,一般用于数据更新操作。
4. DELETE:删除数据,请求参数在URL中传递,一般用于数据删除操作。

一、GET请求

1.前端使用例子:
axios.get('/api/getUserInfo?id=123')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

2.后端使用例子:
@RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
@ResponseBody
public User getUserInfo(@RequestParam("id") String id) {
    User user = userService.getUserById(id);
    return user;
}
```

二、POST请求

1.前端使用例子:
axios.post('/api/login', {
    username: 'admin',
    password: '123456'
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

2.后端使用例子:
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> login(@RequestBody Map<String, Object> params) {
    String username = (String) params.get("username");
    String password = (String) params.get("password");
    // 验证用户名和密码
    // ...
    Map<String, Object> result = new HashMap<>();
    result.put("code", 200);
    result.put("msg", "登录成功");
    return result;
}

三、PUT请求

1.前端使用例子:
axios.put('/api/updateUserInfo', {
    id: 123,
    name: '张三',
    age: 18
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

2.后端使用例子:
@RequestMapping(value = "/updateUserInfo", method = RequestMethod.PUT)
@ResponseBody
public Map<String, Object> updateUserInfo(@RequestBody User user) {
    // 更新用户信息
    Map<String, Object> result = new HashMap<>();
    result.put("code", 200);
    result.put("msg", "更新成功");
    return result;
}

四、DELETE请求

1.前端使用例子:
axios.delete('/api/deleteUser?id=123')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

2.后端使用例子:
@RequestMapping(value = "/deleteUser", method = RequestMethod.DELETE)
@ResponseBody
public Map<String, Object> deleteUser(@RequestParam("id") String id) {
    // 删除用户信息
    // ...
    Map<String, Object> result = new HashMap<>();
    result.put("code", 200);
    result.put("msg", "删除成功");
    return result;
}

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只java小菜鸡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值