如何使用reactjs向服务器发送请求?

时间:2018-03-20 06:10:48

标签: javascript reactjs spring-mvc

我有在jquery和spring mvc开发的web应用程序...一切都很完美......但是现在我想在我的应用程序中使用React JS ...我想在反应中创建一个表单并发送ajax请求我的春天mvc控制器...我知道如何用jquery做但不用反应js ....请告诉我创建表单的方式并发送请求到spring mvc controler .... 这是我的控制器方法,我想得到请求......

@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";

    }

我在stackoverflow中经历了不同的解决方案,并在谷歌搜索但我没有得到任何正确的结果。

4 个答案:

答案 0 :(得分:4)

安装axios

$ npm install axios

导入axios

import axios from 'axios';

示例GET请求

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

示例POST请求

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

答案 1 :(得分:3)

您需要从react.js应用程序向服务器发送XMLHttp请求。 例如:

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

您还可以使用一些漂亮的图书馆,例如axiosfetchsuperagentrequest等。

答案 2 :(得分:2)

通常用于通信的后续API之一是 fetch ,这也正在慢慢成为浏览器标准。

fetch API文档

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

fetch用法

更多信息: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兼容性

由于浏览器并非总是统一,您可以考虑使用填充,例如whatwg-fetch @ https://github.com/github/fetch

表格与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>
    );
  }
}

答案 3 :(得分:0)

使用其中之一:axios、fetch 或 XMLHttpRequest。项目Axios已停止从所有者,fetch使用的代码比axios多,最后一个复杂