简体   繁体   English

无法使用 axios 将数据发送到服务器

[英]not able to send data to server using axios

i am taking the data from form and using submit button i need to send the data to server which is nodejs.我正在从表单中获取数据并使用提交按钮,我需要将数据发送到 nodejs 的服务器。 but i am not able to send the data to server using axios.但我无法使用 axios 将数据发送到服务器。 and also i am not receiving any error what may be the problem?而且我没有收到任何错误可能是什么问题?

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;

I think axios.post should be called from handleSubmit() .我认为axios.post应该从handleSubmit()调用。 Currently your code is using axios in componentDidMount() which is triggered early(automatically) in the lifecycle of your React component.目前您的代码在componentDidMount()使用 axios,它在 React 组件的生命周期中早期(自动)触发。

Everything is proper except the way ur making the post call, componentDidMount get called only once just after the rendering of the component, so u can't make a post call inside this.除了您进行后期调用的方式外,一切都正确, componentDidMount在组件渲染后仅被调用一次,因此您无法在此内部进行后期调用。

From React DOCs : 来自 React DOC

componentDidMount() is invoked immediately after a component is mounted. componentDidMount() 在组件安装后立即调用。 Initialization that requires DOM nodes should go here.需要 DOM 节点的初始化应该在这里进行。 If you need to load data from a remote endpoint, this is a good place to instantiate the network request.如果您需要从远程端点加载数据,这是实例化网络请求的好地方。

Write that post call inside handleSubmit method, it will work, try this:handleSubmit方法中写入 post 调用,它会起作用,试试这个:

componentDidMount(){

}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM