Back-end joint debugging before project development: How to pass parameters/multiple parameters in GET requests

Preface

I still want to tell you something:

All your flaws will be revealed when you do this

I haven’t touched project development for a long time, and I really forgot all about front-end and back-end joint debugging. I reviewed this part of knowledge again today and wrote this note.

text

There are two ways to pass parameters in GET requests:

http://localhost/test/1

http://localhost/test?id=1

Front-end demo

Preliminary preparations

//axios配置
const config:object = {
    //这部分省略...
}

//实例化axios
const service = axios.create(config);

http://localhost/test/params

This method is to pass the request parameters directly after the request path . The code is as follows:

Front-end request api

service.get(`http://localhost/test/${id}`) //占位符直接放入id的值
    .then(res => console.info("请求结果是: ", res));

Backend interface

When writing the backend interface, you need to pay attention to the fact that the formal parameter type needs to be consistent with the path parameter type, and the formal parameter name needs to be consistent with the name in the path parameter placeholder before params can be received.

You can also use @PathVariable(value = "xx")  to specify

@RestController
@Slf4j
public class TestController {
    @GetMapping("/test/{id}")
    //如果不用@PathVariable注解,形参需要与路径占位符中的名称一致,即:id
    public Result queryUser(@PathVariable("id") String userId) {
        //...
        return Result.ok();
    } 
}

http://localhost/test?id=1

The second is to convert the request parameters into strings and concatenate them into the url address behind the request url . The code is as follows:

Front-end request api

service.get('http://localhost/test', { id : 1 })
    .then(res => console.info('请求结果是:', res));

Backend interface

The requirements still require one-to-one correspondence

In this form, if the backend interface parameters do no longer be specified with @PathVariable, but specified with @RequestParam.

@RestController
@Slf4j
public class TestController {
    @GetMapping("/test")
    public Result queryUser(@RequestParam("id") String userId) {
        //...
        return Result.ok();
    }
}

expand

annotation illustrate
@PathVariable Used to receive path parameters, use placeholders to describe path parameters, such as {parameter name}

@RequestParam 

Used to receive URL address parameters or form parameters
@RequestBody Used to receive json data

Afterword

This note is also very basic. It just organizes the easily confused knowledge. It is also a small step in my learning process to regain knowledge.

Preview: "Front-end and back-end joint debugging: How to pass form parameters"

Guess you like

Origin blog.csdn.net/Ccc67ol/article/details/132432662