当前位置: 首页 > article >正文

前端发送请求格式

1.multipart/form-data格式发送请求参数

什么时候用:

  • 当后端API要求以表单的形式接收数据时,比如<input type="text" name="username"><input type="password" name="password">,这些数据通常以键值对的形式发送。
  • 当上传文件时,比如上传图片等等。。。

前端代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>springboot-test</title>
</head>
<body>
    <form>
        <label>用户名:</label>
        <input id="username" type="text" placeholder="username"><br>
        <label>密码:</label>
        <input id="password" type="password" placeholder="password"><br>
        <input id="submit" type="button" value="提交">
    </form>


    <script src="js/axios.min.js"></script>
    <script>
        const username = document.querySelector('#username')
        const password = document.querySelector('#password')
        const submit = document.querySelector('#submit')

        submit.addEventListener('click', async () => {
            const formData = new FormData()
            formData.append('username', username.value)
            formData.append('password', password.value)

            await axios({
                url: 'http://localhost:8080/test',
                method: 'post',
                data: formData
            }).then(result=>{
                console.log(result.data)
            }).catch(error=>{
                console.log(error)
            })
        })
    </script>
</body>
</html>

后端代码: 

package com.akbar.urltest.controller;

import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("test")
public class TestController {

    @PostMapping
    public String formDataTest(String username,String password) {
        System.out.println("----------------------------------------------------");
        System.out.println("username:"+username);
        System.out.println("password:"+password);
        System.out.println("----------------------------------------------------");

        return "后端成功收到username:"+username+",password:"+password;
    }
}

apifox:

 2.query string查询字符串

什么时候用:

  • 当你发送的数据需要附加在URL之后,作为GET请求的一部分时,使用查询字符串(query string)。
  • 当数据简单,如键值对,并且不需要在请求体中发送时。

前端代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>query-string发送请求参数</title>
</head>
<body>
    <form>
        <label>用户名:</label>
        <input id="username" type="text" placeholder="username"><br>
        <label>密码:</label>
        <input id="password" type="password" placeholder="password"><br>
        <input id="submit" type="button" value="提交">
    </form>


    <script src="js/axios.min.js"></script>
    <script>
        const username = document.querySelector('#username')
        const password = document.querySelector('#password')
        const submit = document.querySelector('#submit')

        submit.addEventListener('click', async () => {
            await axios({
                url: 'http://localhost:8080/test',
                method: 'get',
                params:{
                    username: username.value,
                    password: password.value
                }
            }).then(result=>{
                console.log(result.data)
            }).catch(error=>{
                console.log(error)
            })
        })
    </script>
</body>
</html>

后端代码: 

package com.akbar.urltest.controller;

import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("test")
public class TestController {

    @GetMapping
    public String formDataTest(String username,String password) {
        System.out.println("----------------------------------------------------");
        System.out.println("username:"+username);
        System.out.println("password:"+password);
        System.out.println("----------------------------------------------------");

        return "后端成功收到username:"+username+",password:"+password;
    }
}

apifox:

 3.application/json

  • 当你发送的数据是JavaScript对象,并且后端API期望接收JSON格式的数据时,使用application/json
  • 当数据结构复杂,需要以嵌套对象或数组的形式发送时。

前端代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>application/json格式发请求</title>
</head>
<body>
    <form>
        <label>用户名:</label>
        <input id="username" type="text" placeholder="username"><br>
        <label>密码:</label>
        <input id="password" type="password" placeholder="password"><br>
        <input id="submit" type="button" value="提交">
    </form>


    <script src="js/axios.min.js"></script>
    <script>
        const username = document.querySelector('#username')
        const password = document.querySelector('#password')
        const submit = document.querySelector('#submit')

        submit.addEventListener('click', async () => {
            await axios({
                url: 'http://localhost:8080/test',
                method: 'post',
                data:{
                    username: username.value,
                    password: password.value
                }
            }).then(result=>{
                console.log(result.data)
            }).catch(error=>{
                console.log(error)
            })
        })
    </script>
</body>
</html>

虽然我们在data里面写的不是json格式的数据,但是只要我们在data里面用JavaScript对象的格式写数据,axios会帮我们转换成json字符串格式。

后端代码:

package com.akbar.urltest.controller;

import com.akbar.urltest.pojo.User;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("test")
public class TestController {

    @PostMapping
    public String formDataTest(@RequestBody User user) {
        System.out.println("----------------------------------------------------");
        System.out.println("username:"+user.getUsername());
        System.out.println("password:"+user.getPassword());
        System.out.println("----------------------------------------------------");

        return "后端成功收到"+user;
    }
}

因为前端发送的时json字符串格式的对象(我暂时就这么理解的),所以后端接受要用对应的对象接受,比如user对象,然后别忘了用@RequestBody注解。

User.java实体类

package com.akbar.urltest.pojo;

public class User {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

apifox:

4.Path Parameters(路径参数) 

  • 当需要指定资源的唯一标识符时,使用路径参数。例如,获取特定用户的信息,URL可能是/users/{userId},其中{userId}是一个路径参数。
  • 路径参数通常用于GET、PUT、DELETE等请求方法,因为这些方法通常与获取、更新或删除特定资源相关。
  • 路径参数是URL的一部分,因此它们在请求的URL中清晰可见,这有助于客户端和服务器端理解请求的上下文。

前端代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>application/json格式发请求</title>
</head>
<body>
    
    <input id="submit" type="button" value="提交">


    <script src="js/axios.min.js"></script>
    <script>
        submit.addEventListener('click', async () => {
            const id = 1
            await axios({
                url: `http://localhost:8080/test/${id}`,
                method: 'get',
            }).then(result => {
                console.log(result.data)
            }).catch(error => {
                console.log(error)
            })
        })
    </script>
</body>
</html>

后端代码:

package com.akbar.urltest.controller;

import com.akbar.urltest.pojo.User;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("test")
public class TestController {

    @GetMapping("{id}")
    public String formDataTest(@PathVariable Integer id) {
        System.out.println("----------------------------------------------------");
        System.out.println("id:"+id);
        System.out.println("----------------------------------------------------");

        return "后端成功收到:"+id;
    }
}

apifox:


http://www.kler.cn/news/363929.html

相关文章:

  • Ruby 从入门到精通:学习之旅与资源推荐
  • 微信小程序绘制轨迹
  • FFmpeg 库的简要说明
  • WEB前端使用标签制作网页
  • js 填充数组
  • 二百六十八、Kettle——同步ClickHouse清洗数据到Hive的DWD层静态分区表中(每天一次)
  • 2024昆明ICPC A. Two-star Contest(直观命名+详细注释)
  • SpringCloudAlibaba-Nacos
  • upload靶场sql靶场一点点见解
  • 【论文阅读】SRGAN
  • UE5 射线折射
  • Ubuntu22.04虚拟机安装
  • 牛客周赛63
  • 【OpenAI】第六节(语音生成与语音识别技术)从 ChatGPT 到 Whisper 的全方位指南
  • MFF原理描述
  • 2024-1024节
  • MySQL-存储引擎入门概念
  • 2024 Rust现代实用教程:1.1Rust简介与安装更新
  • 对于Windows 11蓝屏代码0x0000003B的研究
  • 【c++小游戏】Surviving版本v0.1.1
  • [LeetCode] 78. 子集
  • 标准函数let、run、also、all、with、takeIf、takeUnless
  • [LeetCode] 207. 课程表
  • 【Java知识】一款强大的SQL处理库JSqlPaser
  • 【优选算法篇】在分割中追寻秩序:二分查找的智慧轨迹
  • Oracle CONNECT BY、PRIOR和START WITH关键字详解