前端发送请求和后端springboot接受参数[前端异步/HTTP方法]

0.xhr、 ajax、axios、promise和async/await 和http基本方法

xhr、 ajax、axios、promise和async/await都是异步编程和网络请求相关的概念和技术!

  • xhr:XMLHttpRequest是浏览器提供的js对象(API),用于请求服务器资源。

    • 在没有xhr的年代,向服务器请求资源时,会返回整个完整的HTML页面,浏览器引擎在渲染新的HTML页面时会导致屏幕闪烁。
    • 如果你用java awt之流手搓过游戏肯定能深刻明白,游戏绘制的闪烁问题使用「双缓冲(存)技术」方案解决
    • 而浏览器上提出方案就是只渲染新的必要的数据而不是整个页面。惟一需要获得整个新 HTML 页面的时候就是希望用户看到新页面的时候。XHR就是这样的技术
  • ajax:Asynchronous JavaScript and XML ,ajax是基于 原生xhr(或fetch)在网页中进行异步通信的技术概念。不刷新整个页面的情况下就可以更新页面内容。

    • ajax 是一种通用的异步通信概念而不是具体的API or lib。以前是用xhr实现,现代也可以用fetch这个浏览器提供API来实现了。类似 现在说"这个问题直接去百度"而不是"这个问题直接去搜索引擎查询"
    • jquery包含的ajax部分就是封装了原生xhr实现的
  • Promise:既是一种解决异步的技术概念,也是在es6提出的处理异步操作的方案JS原生对象(技术实现),通过链式调用来解决ajax的回调地狱。

  • axios:一个基于 Promise 的 HTTP 客户端(lib),用于在浏览器和 Node.js 环境中发起 HTTP 请求。能更简单地执行 HTTP 请求

  • async/await:async/await 是基于 Promise 的语法糖

xhr
ajax
Promise
axios
async/await

总结来说,axios 和 ajax 都是用于进行网络请求的技术,但 axios 是一个独立的库,而 ajax 是一种通用的异步通信概念。
Promise 是一种用于处理异步操作的基础机制,它可以被用于任何需要处理异步的场景,包括网络请求。在es6时引入为JS的原生对象进行概念的落地实现


下面是HTTP 常用方法介绍

  • GET:发送请求,要求服务器返回某个资源。即请求资源
  • PUT: 与GET相反,PUT会向服务器写入(更新or创建)信息(文档)
  • POST:向服务器发送数据。常见的例如发送表单信息
  • DELETE:请求服务器删除指定URL的资源

最容易混淆的是put和post,Google查询为:
The key difference between PUT and POST methods is that a PUT is restricted to create or update operations, while a POST operation may perform any type of processing.
put被限制于 create和update操作,而post则百无禁忌*

Unlike a POST, PUT operations may only operate on the resource identified by the URL provided. HTTP POST processing is allowed on any server-side resource, regardless of the URL.
即PUT 操作只能对提供的 URL 标识的资源进行操作

如果看完上述写Restful接口时仍然分不清post和put话笔者有个小技巧:

  • 前端请求需要提前知道唯一标识符,使用PUT(联想记忆:put的u代表update更新操作)
  • 前端请求结果会生成新的唯一标识符(如数据库表的主键),用post

1.前端发送请求

vue项目中,现在一般都是单独创建axios实例然后默认导出

import axios from ‘axios’
const instance=axios.create({……})
export default instance

具体的接口可以这样导出

import request from '@/utils/request'
export function getSolution(params) {
  return request({
    url: '/api/XXX/data',
    method: 'get',
    params
  })

具体调用时用 Promise 的链式操作处理

import * as xxapi from '@/api/datax-job-project'

 xxapi .getListByUser({ 'username': username }).then(response => {
        this.jobProjectList = response.content.data
      })
1.2 发送请求

http请求发送写法倒是没有很多,主要是参数是否在url上
get、put、post、delete

export function created(data) {
  return request({
    url: '/api/order',
    method: 'post',
    data
  })
}

export function list(params) {
  return request({
    url: '/api/order',
    method: 'get',
    params
  })
}

export function updated(data) {
  return request({
    url: '/api/order',
    method: 'put',
    data
  })
}

export function deleted(data) {
  return request({
    url: '/api/order',
    method: 'delete',
    params: data
  })
}

export function delete(id) {
  return request({
    url: '/api/user/remove?id=' + id,
    method: 'post'
  })
}
  • get方法: 参数通常放在 URL 的查询字符串中,而不是请求体中。例如:GET /users?id=123,get方法直接传params就行了,参组会字段拼在url后面
  • post/put 方法: 参数则会放在请求报文的请求体中,例如JSON 数据,放在请求体中,使用 application/json 编码类型。
  • DELETE 方法:参数通常不会放在请求体中,而是通过 URL 参数或查询字符串来传递。例如:DELETE /users/123
后端接受参数

前后端以json格式进行数据交互,后端springboot项目


前端的post和put方法参数在请求报文的请求体中,所以使用@RequestBody:
后端:

 @PostMapping("/data")
    public ResponseEntity<String> processData(@RequestBody Map<String, Object> requestData) {
        // Process data received from the frontend
        return ResponseEntity.ok("Data processed successfully");
    }

前端方法,传输的是kv结构,后端也用Map结构.

   sendData() {
      const requestData = { key: 'value' }; // Data to be sent to the backend
      axios.post('/api/data', requestData)
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.error(error);
        });
    },

当然,如果你Post方法提交的是表单数据(也就是传统的通过表单提交),以 application/x-www-form-urlencoded 或 multipart/form-data 编码类型发送, 得用@RequestParam


get方法一般使用@RequestParam接受参数,也可以用@PathVariable !
@RequestParam 如果前端key值和形参名称一致,可以不用写@RequestParam

@GetMapping("/api/users")
public ResponseEntity<String> getUsers(@RequestParam("page") int page) {
    // 处理分页参数
    // ...
    return ResponseEntity.ok("Requested page: " + page);
}

// 直接使用方法参数名作为参数名。
// Spring Boot 默认会根据参数名自动进行参数映射
@GetMapping("/api/users")
public ResponseEntity<String> getUsers(int page) {
    // 处理分页参数
    // ...
    return ResponseEntity.ok("Requested page: " + page);
}

当然@RequestParam 可以注解来映射不一样的参数名称
前端发送的请求:

axios.post('/api/endpoint', {
  first_name: 'John',
  last_name: 'Doe',
  user_age: 30
})

后端映射

   @PostMapping("/endpoint")
    public ResponseEntity<String> handlePostRequest(
        @RequestParam("first_name") String firstName,
        @RequestParam("last_name") String lastName,
        @RequestParam("user_age") int age
    ) {
        // 使用参数 firstName、lastName 和 age 来处理请求数据
        // ...
        return ResponseEntity.ok("Request handled successfully");
    }

get使用@PathVariable 注意@GetMapping 需要些占位符,占位符就是形参名称

@GetMapping("/api/users/{userId}")
public ResponseEntity<String> getUserById(@PathVariable Long userId) {
    // 根据 userId 查询用户信息
    // ...
    return ResponseEntity.ok("Requested user ID: " + userId);
}

DELETE 请求和get请求类似,后端 Spring Boot 项目的 Controller 层可以通过 @RequestParam 或 @PathVariable 来接收参数,一般都是后者
前端请求:

axios.delete('/api/users/123')
  .then(response => {
    console.log(response.data); // 输出 "User with ID 123 deleted successfully."
  })
  .catch(error => {
    console.error(error);
  });
  @DeleteMapping("/api/users/{userId}")
    public String deleteUser(@PathVariable Long userId) {
        // 根据 userId 删除用户
        return "User with ID " + userId + " deleted successfully.";
    }

总结
前后端使用json交互情况下,
前端 get put post ,参考示例

api.delete({k:v}).then(response => {
        //
      })

后端接受的话,get一般用@RequestParam(从请求头取参数),put/post用 @RequestBody(从请求体取承参数)


前端 delete方法,注意后端发送拼个唯一标识符

export function deleteUser(id) {
return request({
url: ‘/api/user/’+id,
method: ‘delete’
})
}

后端接收一般delete用 @PathVariable,占位符就是传入形参的名称

 @DeleteMapping("/api/users/{userId}")
    public String deleteUser(@PathVariable Long userId) {
        // 根据 userId 删除用户
        return "User with ID " + userId + " deleted successfully.";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值