2017-01-30 33 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組件的生命週期中提前(自動)觸發。

相關問題