【问题标题】:how to get the values that were sent from axios.post in the backend如何在后端获取从 axios.post 发送的值
【发布时间】:2020-11-01 10:40:54
【问题描述】:

我在前端使用 react,后端使用 springboot。我无法检索在后端使用 axios 发送的数据。下面的第一个代码是我发布并发送我想在后端使用的 3 个对象的前端。第二个代码段是我发布映射的后端,但对于如何获取我从前端发送的这 3 个对象感到非常困惑。此外,用户是我拥有名称、消息和电子邮件的 getter 和 setter 的地方,因此我想将前端的数据设置到 User 中的这些变量中。我对springboot有点陌生,但我在将数据库连接到springboot方面有一些经验,但在这种情况下,我不需要使用数据库来存储任何东西。我的总体目标是实现一个有效的联系表单,用户可以在其中提交有关网页的 cmets/投诉,并将这些电子邮件发送给我。

const info = {
    name: "Test" 
    message: "This is comment for test",
    email: "test@test.com  
};
        
axios.post("http://localhost:8080/postgressApp/signup-success", info)
   .then(response => {
       if(response.data != null) {
          this.setState({show:true});
          setTimeout(() => this.setState({show:false}), 3000);
          window.location.reload();
       } else {
          this.setState({show:false});
       }
    });
@RestController
@RequestMapping("/postgressApp")
@CrossOrigin(origins="http://localhost:3000")
public class RegistrationController {
    
    private Logger logger = LoggerFactory.getLogger(RegistrationController.class);
    
    @Autowired
    private NotificationService notificationService;
    
    @PostMapping("/signup-success")
    public String signupSuccess(){
        
        // create user 
        User user = new User();
        
        // send a notification
        try {
            notificationService.sendNotificaitoin(user);
        }catch( MailException e ){
            // catch error
            logger.info("Error Sending Email: " + e.getMessage());
        }
        
        return "Thank you for registering with us.";
    }
    
}

【问题讨论】:

    标签: javascript reactjs spring-boot spring-boot-maven-plugin


    【解决方案1】:

    像这样改变你的方法签名:

    ...
    @PostMapping("/signup-success")
    public String signupSuccess(@RequestBody User user) {
    ...
    }
    

    @RequestBodyannotation 告诉 Spring 将传入的 http 请求的主体绑定到您的类型。它将检查您的请求参数键和值,检查您在注释后提供的类型,尝试将参数键与您的用户类中的字段匹配,然后将值从请求复制到您的用户实例。

    【讨论】:

    • 非常感谢您的解释。
    猜你喜欢
    • 2020-03-04
    • 2019-09-17
    • 2022-07-08
    • 1970-01-01
    • 2021-11-24
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多