所以我在React上使用axios.post 这是我的代码
反应GenService.jsx
import axios from "axios";
import { Route, withRouter } from "react-router-dom";
const COURSE_API_URL = "http://localhost:8080";
class GenService {
retrieveAll() {
return axios.get(`${COURSE_API_URL}`);
}
pAll() {
return axios.post(`${COURSE_API_URL}` + "/user", {
firstName: "Fred",
lastName: "Flintstone"
});
}
}
export default new GenService();
但是我不知道如何使用Spring Boot在后端Java中调用firstName和lastName
SpringBootLd2nlApplication.java
package com.ld2nl.springbootld2nl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@SpringBootApplication
@CrossOrigin(origins = { "http://localhost:3000", "http://localhost:4200" })
@RestController
public class SpringBootLd2nlApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootLd2nlApplication.class, args);
}
//works
@RequestMapping(value = "/")
public String say() {
return "Sending Hello To React";
}
//not work
@RequestMapping(value = "/user")
public String reply(@RequestParam String firstName) {
return firstName;
}
}
如您所见,无法获得标记为“ //不起作用”的区域来正确调用firstName和lastName
当前出现错误
Required String parameter 'firstName' is not present
....
答案 0 :(得分:0)
与其试图直接获取在POST时不起作用的参数,还不如将其作为有效载荷/ JSON对象发送数据,而不是按参数拆分,以下方法应该起作用:
@PostMapping(value = "/user")
public String reply(@RequestBody Map<String, Object> payLoad) {
return (String)payLoad.get("firstName");
}
答案 1 :(得分:0)
不要像这样传递名字,而是尝试为名字创建一个const。
const firstName = "Fred";
...
...
pAll(){
return axios.post(http://localhost:8080/users/${firstname});
}
然后在Springboot中,将这些行添加到reply()函数中
@GetMapping("/users/{firstname}
public String reply(@PathVariable String firstName) {
return firstName;
}
答案 2 :(得分:0)
最好的方式(生产方式)是提供单独的 DTO。
public class SendMessageDto {
@NotBlank @Length(min=4)...
private String userName;
public String getUserName() {return this.userName} ;
}
在控制器中
@PostMapping(value = "/user")
public String reply(@Valid @RequestBody SendMessageDto) { //
return payLoad.getUserName();
}