Knowledge that needs to be memorized Seven front-end and back-end parameter transfer types

quick preview

  1. Query Parameters: Add parameters to the end of the URL, separated by ?and . &For example: https://example.com/search?q=keyword&page=2.

  2. Path Parameters (Path Parameters): Add parameters to the path of the URL, /separated by . For example: https://example.com/users/{id}.

  3. Request Body Parameters (Request Body Parameters): Pass the parameters in the request body, which is suitable for situations where there are many or large parameters. Commonly used formats are JSON, XML, etc.

  4. Form Data: Pass parameters in the form of the HTTP request, applicable to scenarios such as submitting forms or uploading files.

  5. Header Parameters (Header Parameters): Add parameters to the HTTP request header for delivery, usually used to pass authentication information or other metadata.

  6. Cookie Parameters (Cookie Parameters): Add parameters to the Cookie of the HTTP request for delivery, usually used to store session information or other identifiers.

  7. File Upload: Place the file in the request body for delivery, usually using multipart/form-datathe format.

text

query parameters

When we need to attach request parameters to the URL, we can use query parameters (Query Parameters). Query parameters are a list of key-value pairs separated by question marks (?), and multiple parameters are separated by & symbols. For example:

https://example.com/articles?category=technology&sort=desc&page=1
复制代码

In this example, we append three parameters category, sort and page to the URL. The value of category is technology, the value of sort is desc, and the value of page is 1.

An example of the front end using the Axios library to send a GET request with query parameters is as follows:

front end

// 使用GET方法请求文章数据,将查询参数附加到URL上
const params = {
  category: 'technology',
  sort: 'desc',
  page: 1
};
axios.get('https://example.com/articles', { params })
  .then(response => {
    const data = response.data;
    // 处理文章数据
  })
  .catch(error => console.error(error));
复制代码

在这个示例中,我们将查询参数以JavaScript对象的形式传递给Axios库的get()方法,并通过第二个参数的params选项来将它们附加到URL上。在后端,我们可以使用Spring Boot框架的@RequestParam注解来声明接收查询参数的方法参数。例如:

后端

@GetMapping("/articles")
public ResponseEntity<List<Article>> getArticles(
    @RequestParam("category") String category,
    @RequestParam("sort") String sort,
    @RequestParam("page") int page) {
  // 处理文章数据
  List<Article> articles = articleService.getArticles(category, sort, page);
  return ResponseEntity.ok(articles);
}
复制代码

在这个示例中,我们使用Spring Boot框架的@GetMapping注解来声明一个处理GET请求的方法,其中"/articles"表示请求路径。在方法参数中,我们使用@RequestParam注解来声明三个接收查询参数的方法参数,它们的名称必须与查询参数的键名称相同。在方法体内,我们调用了一个名为getArticles()的方法来从数据库中获取符合查询参数条件的文章数据,并将其封装到一个ResponseEntity对象中返回。

路径参数

路径参数(Path Parameters)是一种常见的前后端数据传递方式,用于向服务器传递变量或参数值,通常出现在URL路径中的一部分,用于描述请求的资源。

在前端,通常使用请求库Axios 构建一个带有路径参数的请求,以便向后端服务器发送请求。

在后端,使用路由Spring Boot等来定义响应请求的控制器方法,并从路径参数中读取请求所需的参数值。

以下是一个基于Axios和Spring Boot的路径参数示例:

前端

// 使用GET方法请求文章数据,将文章ID作为URL路径参数传输
const articleId = 123;
axios.get(`https://example.com/articles/${articleId}`)
  .then(response => {
    const data = response.data;
    // 处理文章数据
  })
  .catch(error => console.error(error));
复制代码

后端

@RestController
@RequestMapping("/articles")
public class ArticleController {
  @Autowired
  private ArticleService articleService;

  @GetMapping("/{id}")
  public ResponseEntity<Article> getArticle(@PathVariable("id") Long id) {
    // 处理文章数据
    Article article = articleService.getArticle(id);

    if (article == null) {
      // 如果找不到对应的文章,则返回404 Not Found响应
      return ResponseEntity.notFound().build();
    } else {
      // 返回包含文章数据的200 OK响应
      return ResponseEntity.ok(article);
    }
  }
}
复制代码

在这个示例中,我们使用Axios库的get()方法发送一个GET请求,请求地址为https://example.com/articles/123,其中123是文章的ID。这个请求将返回文章的JSON数据,并使用response.data属性将其解析为JavaScript对象

在后端,我们使用Spring Boot框架的@GetMapping注解来声明一个GET请求处理方法,其中"/articles/{id}"表示请求路径中的文章ID会作为方法参数中的id变量传入。

请求体参数

请求体参数通常用于传递更复杂的数据,例如提交一个表单或创建一个资源。这种类型的参数通常使用POST或PUT请求来发送到服务器端,并使用请求体(Request Body)将数据作为JSON格式或表单数据进行传输。

我们来看一个示例,前端使用Axios库来发送一个POST请求,请求体包含一个名为title和一个名为content的字段:

前端

// 使用POST方法提交表单数据
const formData = {
  title: '标题',
  content: '正文内容',
};
axios.post('https://example.com/articles', formData)
  .then(response => {
    const data = response.data;
    // 处理服务器返回的响应
  })
  .catch(error => console.error(error));
复制代码

在这个示例中,我们使用Axios库的post()方法来发送一个POST请求,请求地址为https://example.com/articles,请求体参数为formData对象。这个请求将提交一个表单,其中包含一个标题和正文内容。 接下来,我们看一下服务器端如何接收这个请求体参数。后端使用Java语言编写,我们可以使用Spring Boot框架的@RequestBody注解将请求体参数映射到Java对象中:

后端


@PostMapping("/articles")
public ResponseEntity<Article> createArticle(@RequestBody ArticleRequest request) {
  // 从请求体参数中获取文章标题和内容
  String title = request.getTitle();
  String content = request.getContent();
  // 创建文章并保存到数据库中
  Article article = articleService.createArticle(title, content);
  // 创建成功后返回一个包含文章数据的响应
  return ResponseEntity.ok(article);
}
复制代码

在这个示例中,我们使用Spring Boot框架的@PostMapping注解来声明一个POST请求处理方法,其中"/articles"表示请求路径。在方法体内,我们使用@RequestBody注解将请求体参数映射到ArticleRequest对象中,该对象包含文章的标题和内容。然后,我们调用一个名为createArticle()的方法来创建一篇文章,并将其保存到数据库中。最后,我们使用ResponseEntity.ok()方法创建一个包含文章数据的成功响应。

请求体参数通常用于传递更复杂的数据。在前端使用Axios库发送POST或PUT请求时,可以将请求体数据作为一个对象传递。在后端使用Spring Boot框架时,可以使用@RequestBody注解将请求体参数映射到Java对象中,然后进行相应的处理。

表单数据

在前端使用 Axios 发送 POST 请求时,我们可以使用 Axios 提供的 post() 方法,并将参数作为一个对象传入。在发送请求时,我们需要将 Content-Type 设置为 application/x-www-form-urlencoded。这是因为表单数据的格式是 key1=value1&key2=value2 这样的形式,需要使用这种格式来将表单数据传递给后端。

以下是一个前端使用 Axios 发送表单数据的示例代码:

前端

// 使用 POST 方法向服务器提交表单数据
const formData = new FormData();
formData.append('username', 'admin');
formData.append('password', '123456');
axios.post('https://example.com/login', formData, {
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
  .then(response => {
    const data = response.data;
    // 处理响应数据
  })
  .catch(error => console.error(error));
复制代码

在这个示例中,我们使用 Axios 的 post() 方法发送一个 POST 请求,将用户名和密码作为表单数据传递给服务器。我们首先创建了一个 FormData 对象,然后使用 append() 方法将参数添加到 FormData 中。最后,在发送请求时,我们将 FormData 对象作为请求体传递给服务器,并将 Content-Type 设置为 application/x-www-form-urlencoded。

接下来我们来看一下后端如何接收表单数据。假设我们使用了 Spring Boot 框架,以下是一个使用 @PostMapping 注解处理表单数据的示例代码:

后端

@PostMapping("/login")
public ResponseEntity<String> login(@RequestParam("username") String username, @RequestParam("password") String password) {
  // 处理登录逻辑
  if (username.equals("admin") && password.equals("123456")) {
    return ResponseEntity.ok("登录成功");
  } else {
    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码错误");
  }
}
复制代码

在这个示例中,我们使用 Spring Boot 的 @PostMapping 注解声明了一个 POST 请求处理方法,并将请求路径设置为 /login。我们使用 @RequestParam 注解将表单数据中的参数映射到方法的参数中,从而可以方便地获取这些参数的值。在方法体内,我们可以对这些参数进行逻辑处理,最后使用 ResponseEntity 返回响应结果。

需要注意的是,使用 @RequestParam 注解时,如果请求中的参数名与方法参数名不一致,需要使用 @RequestParam("参数名") 的形式来指定参数名。

除了表单数据,我们还可以使用其他类型的请求体参数进行参数传递,比如 JSON 数据和文件数据。对于不同的请求体参数类型,我们需要使用不同的 Content-Type 类型来指定请求体的格式,从而让服务器能够正确地解析请求体中的参数。

头部参数

头部参数(Header Parameters)是HTTP请求头中包含的一些参数,用于传递与请求内容相关的附加信息,比如请求的认证信息、用户代理信息、内容类型等。

在前端使用Axios库时,可以在请求中通过headers选项来设置请求头参数。例如:

前端

axios.get('/articles', {
  headers: {
    'Authorization': 'Bearer token',
    'Content-Type': 'application/json'
  }
})
复制代码

在这个示例中,我们使用了Axios库的get()方法来发送一个GET请求,并通过headers选项设置了两个请求头参数:Authorization和Content-Type。Authorization参数用于传递请求的认证信息,Content-Type参数用于设置请求的内容类型。

在后端使用Java语言时,可以通过Spring框架中的@RequestHeader注解来获取请求头参数。例如:

后端

@GetMapping("/articles")
public ResponseEntity<List<Article>> getArticles(@RequestHeader("Authorization") String authorization) {
  // 处理请求头参数
}
复制代码

在这个示例中,我们使用了Spring框架的@GetMapping注解来声明一个GET请求处理方法,并通过@RequestHeader注解获取了请求头参数Authorization。这个参数将作为方法参数authorization的值传入,供后续处理使用。

除了上述例子中的Authorization和Content-Type参数之外,常见的头部参数还包括:

  • User-Agent:用户代理信息,用于告诉服务器请求的客户端是什么类型的浏览器或其他应用程序;
  • Accept:告诉服务器客户端期望接收的响应内容类型;
  • Referer:表示请求的来源页面,在有些情况下可以用于防止CSRF攻击;
  • Cookie:表示客户端传递的Cookie信息。

在实际开发中,需要根据具体的业务需求和开发框架来选择合适的头部参数类型,并合理设置请求头参数。

Cookie参数

当我们需要在客户端和服务器之间传递小型数据时,可以使用 Cookie 参数。Cookie 参数是通过在客户端中存储一个小文本文件来实现的。在每个后续请求中,客户端会自动将这个文本文件发送回服务器,以便服务器可以读取它。在前后端应用中,Cookie 参数通常用于存储用户的身份验证令牌或其他应用数据。

下面是一个使用 Cookie 参数的示例,我们将使用 Axios 库在前端发送请求,而后端是基于 Spring Boot 框架开发的 Java 应用程序。假设我们有一个名为“username”的 Cookie,它包含当前用户的用户名。我们将使用 Axios 发送一个 GET 请求,该请求将请求处理方法中使用 @CookieValue 注解从 Cookie 中读取用户名。

前端

axios.get('https://example.com/user-info', {
  withCredentials: true
})
  .then(response => {
    const data = response.data;
    // 处理响应数据
  })
  .catch(error => console.error(error));
复制代码

在这个示例中,我们使用 Axios 库的 get() 方法发送一个 GET 请求,请求地址为 https://example.com/user-info。我们还将 withCredentials 参数设置为 true,以确保 Axios 在发送请求时将包括 Cookie 数据。在成功接收到响应后,我们可以通过 response.data 属性来获取响应数据。

后端

@GetMapping("/user-info")
public ResponseEntity<UserInfo> getUserInfo(@CookieValue(value = "username") String username) {
  // 处理请求,使用 Cookie 中的用户名获取用户信息
  UserInfo userInfo = userService.getUserInfo(username);
  return ResponseEntity.ok(userInfo);
}
复制代码

在这个示例中,我们使用 Spring Boot 框架的 @CookieValue 注解来声明一个 Cookie 参数,该参数将从名为“username”的 Cookie 中读取用户的用户名。在方法体内,我们使用这个用户名来获取用户信息,并返回一个包含用户信息的 ResponseEntity 对象。

以上是使用 Cookie 参数进行前后端数据传递的一个示例,通过在客户端和服务器之间传递 Cookie 数据,我们可以方便地在应用程序中传递小型数据。

文件上传

文件上传是一种常见的前后端参数传递方式,通常用于上传用户上传的图片、音视频等多媒体文件。在前端,我们可以使用Axios库的post()方法来发送一个POST请求,将文件作为请求体进行上传。在后端,我们可以使用Spring Boot框架的MultipartFile类来接收上传的文件数据。

前端代码

下面是一个使用Axios上传文件的示例:

// 选择一个文件
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];

// 创建一个FormData对象,用于将文件数据作为请求体上传
const formData = new FormData();
formData.append('file', file);

// 发送POST请求,将FormData对象作为请求体上传
axios.post('https://example.com/upload', formData)
  .then(response => {
    // 处理上传成功后的响应数据
    console.log(response.data);
  })
  .catch(error => {
    // 处理上传失败的情况
    console.error(error);
  });
复制代码

在这个示例中,我们使用了input元素来让用户选择要上传的文件,然后使用FormData对象将文件数据作为请求体进行上传。在Axios的post()方法中,我们将请求地址设为https://example.com/upload,将FormData对象作为请求体进行上传。如果上传成功,Axios将返回一个包含响应数据的Response对象,我们可以使用response.data属性来获取这些数据。

后端代码

下面是一个使用Spring Boot接收上传文件的示例:

@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
  // 将上传的文件保存到服务器中
  try {
    File dest = new File("/path/to/save/uploaded/file");
    file.transferTo(dest);
    return ResponseEntity.ok("File uploaded successfully");
  } catch (IOException e) {
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file");
  }
}
复制代码

在这个示例中,我们使用了Spring Boot框架的@PostMapping注解来声明一个处理文件上传请求的方法。方法参数中的@RequestParam("file")注解表示请求中名为"file"的参数将被映射到file参数中

注意事项

在使用文件上传时,需要注意以下几个事项:

  • 文件上传请求的Content-Type需要设置为"multipart/form-data";
  • 在前端使用FormData对象将文件数据作为请求体上传时,需要使用append()方法来添加文件数据;
  • 在后端使用MultipartFile类接收文件数据时,需要使用@RequestParam注解来映射请求参数;
  • 在后端处理文件上传请求时,需要注意文件保存路径的权限问题,避免因权限不足而导致文件保存失败。

总结

不同的参数传输方式有其各自的优缺点,我们需要根据实际业务场景来选择最合适的方式。

  • 查询参数(Query Parameters):常用于GET请求,可以直接暴露在URL中,方便调试和传递简单参数。但是对于大量参数或者参数包含敏感信息时,不适合使用查询参数传递。

  • 请求体参数(Request Body Parameters):可以传递大量的数据和复杂的结构体数据,适合于POST、PUT、PATCH等请求。但是需要在前后端都进行序列化和反序列化,相对比较复杂。

  • 路径参数(Path Parameters):常用于RESTful API中,可以让URL更加语义化。但是对于大量参数或者参数长度过长时,不适合使用路径参数传递。

  • 头部参数(Header Parameters):可以用于身份验证等场景,相对比较安全。但是需要在前后端都进行设置和读取,相对比较麻烦。

  • Cookie参数(Cookie Parameters):可以用于跟踪用户状态等场景。但是需要在前后端都进行设置和读取,相对比较麻烦,而且可能会受到浏览器的限制。

  • 表单数据(Form Data):常用于提交表单数据,可以直接将表单数据序列化成键值对。但是对于复杂的结构体数据,不太适合使用表单数据传递。

  • 文件上传(File Upload):可以上传大文件或者二进制文件,适合于POST请求。但是需要在前后端都进行设置和读取,相对比较麻烦,而且需要考虑文件大小和上传进度等问题。

本文正在参加「金石计划」

Guess you like

Origin juejin.im/post/7218778345902850106