Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send request to server with reactjs?

I have a web application that is developed in jquery and spring mvc...all is working perfectly...but now I want to use React JS in my application...i want to create a form in react js and send ajax request to my spring mvc controller...I know how to do it with jquery but not with react js....kindly tell me a way to create a form and send a request to the spring mvc controler.... this is my controller method where I want to get request...

@RequestMapping(value = "/saveuser", method = RequestMethod.POST)
    public @ResponseBody String Save(/*@Valid Users user, BindingResult result,*/HttpServletRequest request, Model model, 
            @RequestParam(required = false) Boolean reverseBeforeSave) {
   
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        String firstName = request.getParameter("first_name");
        String lastName = request.getParameter("last_name");
        System.out.println("save method");
        String[] roleNames = request.getParameterValues("roles");

        userService.saveUserandRoles(userName, password, firstName, lastName, roleNames);
        return "success";
        
    }

I went through different solutions in StackOverflow and have searched on google but I am not getting any proper result.

like image 626
Ahmad Avatar asked Mar 20 '18 06:03

Ahmad


1 Answers

Install axios

$ npm install axios

Import axios

import axios from 'axios';

Example GET request

axios.get('https://api.example.com/')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Example POST request

var body = {
    firstName: 'testName',
    lastName: 'testLastName'
};

axios.post('https://api.example.com/', body)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
like image 96
rajpoot rehan Avatar answered Sep 29 '22 20:09

rajpoot rehan