2017-01-30 34 views
-2

我正在从窗体中获取数据并使用提交按钮我需要将数据发送到服务器,它是nodejs。但我无法使用axios将数据发送到服务器。并且我也没有收到任何错误,可能是什么问题?无法使用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; 

回答

0

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

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

雅在我的服务器端的只显示花括号 –

+0

如何确保数据从反应是否正确发送到服务器 –

+0

在开发者模式下转到网络,当你的应用程序发出任何请求时,它会通过url传递给你,并且你传入的所有参数都只是在头文件中检查后调用字符串参数,如果它显示的是正确的参数,那么前端部分没有错误。 –

0

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

相关问题