首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在后台获取axios.post发来的值

如何在后台获取axios.post发来的值
EN

Stack Overflow用户
提问于 2020-07-12 06:59:34
回答 1查看 127关注 0票数 0

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

代码语言:javascript
复制
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});
       }
    });
代码语言:javascript
复制
@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.";
    }
    
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-12 07:17:40

更改您的方法签名,如下所示:

代码语言:javascript
复制
...
@PostMapping("/signup-success")
public String signupSuccess(@RequestBody User user) {
...
}

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62855460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档