![](/img/trans.png)
[英]How to connect backend create user function to front end (Node.js, React.js, MongoDB)
[英]What is the best way to connect react.js UI to my node.js API and mongoDB?
我正在做我的第一個項目,想知道socket.io是將UI連接到節點的唯一還是最好的解決方案。
您還有什么可以推薦我的嗎? 實時並不重要,我只想訪問我的數據。 簡單的關鍵字已經對我有很大幫助。
謝謝! GT
這很簡單:
確保您的node.js服務器在某些調用上返回(JSON)數據,例如
//this is your API endpoint
app.use('/api/endpoint', (req, res, next) => {
res.send({
key: 'value'
});
});
//this sends your html file with react bundle included
//has to be placed after the api handling
app.use('*', (req, res, next) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
您不必在同一服務器上提供html,但這通常很有意義。
現在,您可以在React應用程序中進行API調用以獲取數據。 我喜歡使用axios( https://github.com/mzabriskie/axios ),但是您可以根據需要撥打電話。
您應該撥打電話並以某種方式保存它,無論是在州內還是在商店中(如果您使用redux)。
例如:
...
componentDidMount() {
axios.get('http://yourserver.com/api/endpoint')
.then(function (response) {
this.setState({
data: response.data
});
})
.catch(function (error) {
console.log(error);
});
}
...
將數據發送到節點服務器以將其存儲在數據庫中非常相似。
請注意,這只是一個基本示例,您在使用過程中會遇到一些問題,尤其是在生產時,例如CSRF保護或用於保護API的JWT。 但是,這應該可以幫助您入門!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.