Ahmad
Ahmad

Reputation: 1474

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.

Upvotes: 7

Views: 26587

Answers (4)

user13423787
user13423787

Reputation:

Use one of this: axios,fetch or XMLHttpRequest. Project Axios has stoped from owner, fetch use more codes than axios and the last one is complex

Upvotes: 0

rajpoot rehan
rajpoot rehan

Reputation: 465

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);
  });

Upvotes: 10

Matyas
Matyas

Reputation: 13702

One of the later APIs usually used for communicating is fetch, that is also slowly becoming a browser standard.

fetch API Doc

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

fetch Usage

More at: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

    fetch('http://example.com/movies.json', { // optional fetch options
        body: JSON.stringify(data), // you may send any data, encoded as you wish. shall match content-type 
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, same-origin, *omit
        headers: {
          'content-type': 'application/json'
        },
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, cors, *same-origin
        redirect: 'follow', // *manual, follow, error
        referrer: 'no-referrer', // *client, no-referrer
    })
    .then(function(response) {
        // manipulate response object
        // check status @ response.status etc.
        return response.json(); // parses json
    })
    .then(function(myJson) {
        // use parseed result
        console.log(myJson);
    });

Crossbrowser compatibility

Since browsers are not always uniform, you might consider using a polyfill, like whatwg-fetch @ https://github.com/github/fetch

Form in react with fetch

import React from 'react';

export class ReactForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        username: '',
        password: '',
        first_name: '',
        last_name: '',
    };
  }

  onSubmit(e) {
    e.preventDefault();
    fetch('http://example.com/movies.json', {
      body: JSON.stringify(this.state),
      cache: 'no-cache',
      credentials: 'same-origin',
      headers: {
        'content-type': 'application/json'
      },
      method: 'POST',
      mode: 'cors',
      redirect: 'follow',
      referrer: 'no-referrer',
    })
      .then(function (response) {
        console.log(response);
        if (response.status === 200) {
          alert('Saved');
        } else {
          alert('Issues saving');
        }
        // you cannot parse your "success" response, since that is not a valid JSON
        // consider using valid JSON req/resp pairs.
        // return response.json();
      });

  }

  render() {
    return (
      <form onSubmit={this.onSubmit.bind()}>
        <input type="text" name="username" onChange={e => this.setState({username: e.target.value})}/>
        <input type="password" name="password" onChange={e => this.setState({password: e.target.value})}/>
        <input type="text" name="first_name" onChange={e => this.setState({first_name: e.target.value})}/>
        <input type="text" name="last_name" onChange={e => this.setState({last_name: e.target.value})}/>
        <button type="submit">Submit</button>
      </form>
    );
  }
}

Upvotes: 3

Vikramaditya
Vikramaditya

Reputation: 5574

You need to send XMLHttp Request to server from your react.js application. example:

var http = new XMLHttpRequest();
var url = "http://<server-url>/saveuser";
var params = "param1=param1Value&param2=param2Value";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {
  if(http.readyState == 4 && http.status == 200) {
      alert(http.responseText);
  }
}
http.send(params);

you can also use some beautiful libraries like axios, fetch, superagent, request etc.

Upvotes: 3

Related Questions