2016-11-14 36 views
-1

使用React應用程序訪問API的最佳方式是什麼?該API目前在Golang中使用kami & mgo用於POST/GET/DELETE請求。從React App訪問API的最佳方式?

我希望能夠做一個GET請求到以下網址:對我作出反應的應用程序

http://user:[email protected]:8000/api/v1/systems

和結果存儲在狀態屬性:

this.state = { 
    data: //store the data here 
} 

我也想要在加載頁面時加載這些數據,所以也許我應該使用componentDidMount()函數來處理這個問題?

我從來沒有在React上使用API​​調用,所以我想知道這裏有人能告訴我一個很好的方法嗎?

編輯

我使用15.3.2作出反應。

編輯#2

我已經採取了看看來處理請求,但我仍然不確定如何在我的情況下使用它。我有在本地主機上運行的應用程序的反應:3000和運行於本機API:8000/API/V1 /系統會返回一個JSON格式如下:

{ systems : [ //list of objects ] } 

我試過裏面以下我componentDidMount():

fetch(myRequest) 
    .then(result => { 
    console.log(result); 
    //this.setState({ data: result.json() }); 
    }); 

不太清楚什麼myRequest應該(在試圖與URL的一個簡單的字符串:「http://localhost:8000/api/v1/systems」),我也不敢肯定,如果在正在運行的應用可以在港口發生衝突或什麼。

+0

可能重複:http://stackoverflow.com/questions/31840412/reactjs-promises-how-should-we-use-it –

回答

1

您將不得不決定一個庫來執行API調用。一個簡單的方法是使用fetch,它是現代瀏覽器中內置的。有一個polyfill覆蓋較舊的。 jQuery's AJAXSuperAgent是兩種選擇。這裏有一個簡單的例子,使用fetch。您只需更改請求的網址。

class Example extends React.Component { 
 
    constructor() { 
 
    super(); 
 
    this.state = { data: {} }; 
 
    } 
 
    componentDidMount() { 
 
    var self = this; 
 
    fetch('http://reqres.in/api/users') 
 
     .then(function(response) { 
 
     return response.json() 
 
     }).then(function(data) { 
 
     self.setState({ data },() => console.log(self.state)); 
 
     }); 
 
    } 
 
    render() { 
 
    return (
 
     <div/> 
 
    ); 
 
    } 
 
} 
 

 
ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="View"></div>

+0

嘗試這個,當我得到以下錯誤: 'localhost /:1 Fetch API無法加載http:// localhost:8000/api/v1/systems。請求的資源上沒有「Access-Control-Allow-Origin」標題。原因'http:// localhost:3000'因此不被允許訪問。響應的HTTP狀態碼爲401.如果一個不透明的響應滿足您的需求,請將請求的模式設置爲'no-cors',以取消禁用CORS的資源。' 'undefined:1未捕獲(承諾中)TypeError:無法獲取 at TypeError(native)' – Tuco

+0

因此,React代碼工作併發出GET請求,但您的服務器不允許CORS。您需要設置Access-Control-Allow-Origin標題。這裏是[一個指針](http://stackoverflow.com/a/12830156/6941627)。 –