Shalin Patel
Shalin Patel

Reputation: 179

how to get the values that were sent from axios.post in the backend

I am using react for the frontend and springboot for the backend. I am not able to retrieve the data that I sent using axios in the backend. The first code below is the frontend where I make post and send 3 objects that I want to use in the backend. And the second code segment is the backend where I have post mapping but really confused on how to get those 3 objects that I sent from frontend. Also the user is where I have the getter and setters for name, message, and email so I want to set the data from frontend into those variables in User. I am somewhat new to springboot but I have some experience in connecting database to springboot but in this case I dont need to use database to store anything. The overall goal is for me to achieve a working contact form where users can submit comments/complaints about a webpage and it will direct those emails to me.

const info = {
    name: "Test" 
    message: "This is comment for test",
    email: "[email protected]  
};
        
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.";
    }
    
}

Upvotes: 0

Views: 847

Answers (1)

ardatosun
ardatosun

Reputation: 467

Change your method signature like this:

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

@RequestBodyannotation tells Spring to bind the incoming http request's body to your type. It will check your request parameter keys and values, check the type you provided after the annotation, try to match parameter keys with the fields in your User class and then copy the values from request to your User instance.

Upvotes: 2

Related Questions