【问题标题】:not able to send data to server using axios无法使用 axios 向服务器发送数据
【发布时间】:2017-06-15 05:46:42
【问题描述】:

我从表单中获取数据并使用提交按钮我需要将数据发送到服务器,即 nodejs。但我无法使用 axios 将数据发送到服务器。而且我没有收到任何错误可能是什么问题?

import React from 'react';
import axios from 'axios';
class Createstudent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
  this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert(this.state.value);

  }

  componentDidMount(){
    axios.post('http://localhost:8080/create',{value:this.state.value})
    .then(function(response){
      console.log(response);
    })
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

export default Createstudent;

【问题讨论】:

    标签: node.js reactjs


    【解决方案1】:

    一切都是正确的,除了你打电话的方式, componentDidMount 在组件渲染后只被调用一次,所以你不能在这个里面进行 post 调用。

    From React DOCs:

    componentDidMount() 在组件被调用后立即调用 安装。需要 DOM 节点的初始化应该放在这里。如果你 需要从远程端点加载数据,这是一个很好的地方 实例化网络请求。

    handleSubmit 方法中编写该帖子调用,它会起作用,试试这个:

    componentDidMount(){
    
    }
    
    handleSubmit(event) {
        alert(this.state.value);
        axios.post('http://localhost:8080/create',{value:this.state.value})
          .then(function(response){
             console.log(response);
           })
    }
    

    【讨论】:

    • 在我的服务器端它只显示花括号
    • 如何确保来自 react 的数据正确发送到服务器
    • 在开发者模式下转到网络,当你的应用程序发出任何请求时,它会带着 url 和你传入的所有参数到达那里,只需检查标题中的 post call 字符串参数,如果它显示正确参数然后前端部分没有错误。
    • 查看此图片如何查看请求及其参数:imgur.com/2pGPHAx
    【解决方案2】:

    我认为应该从handleSubmit() 调用axios.post。目前,您的代码在 componentDidMount() 中使用 axios,它在 React 组件的生命周期中早期(自动)触发。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      • 2019-10-24
      • 2012-11-29
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多