【问题标题】:how to send request to server with reactjs?如何使用 reactjs 向服务器发送请求?
【发布时间】:2018-08-28 20:42:39
【问题描述】:

我有一个使用 jquery 和 spring mvc 开发的 Web 应用程序...一切运行良好...但是现在我想在我的应用程序中使用 React JS...我想在 react js 中创建一个表单并将 ajax 请求发送到我的 spring mvc 控制器...我知道如何使用 jquery 但不使用 react js ....请告诉我一种创建表单并向 spring mvc 控制器发送请求的方法...。 这是我想要获取请求的控制器方法...

@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 中浏览了不同的解决方案,并在 google 上进行了搜索,但没有得到任何正确的结果。

【问题讨论】:

    标签: javascript reactjs spring-mvc


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您需要从您的 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 等。

      【讨论】:

      • 能否为 React js 表单添加代码...我不知道如何在 react js 中创建表单...
      【解决方案3】:

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

      fetchAPI文档

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

      跨浏览器兼容性

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

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

      【讨论】:

      • 能否为 React js 表单添加代码...我不知道如何在 react js 中创建表单...
      • @Ahmad :我提供了一个反应表单示例。但是,如何组装整个 React 应用程序还有更多内容。但至少你有一些开始
      • 好的,谢谢...但是请告诉我如何在我的应用程序中配置 React JS,给我更多的帮助?你能告诉我在我的应用程序中配置 React JS 的整个流程然后创建表单然后向我的控制器发送请求....
      • 我建议您从这里开始:github.com/facebook/create-react-app。答案并不是要详细说明如何设置和开发整个项目。
      【解决方案4】:

      使用以下之一:axios、fetch 或 XMLHttpRequest。 Project axios 已停止所有者,fetch 使用的代码比 axios 多,最后一个复杂

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多