如何与Flask服务器(后端)通信以从React Native前端发送信息? [英] How to communicate with a flask server (backend) to send it information from a react native frontend?
本文介绍了如何与Flask服务器(后端)通信以从React Native前端发送信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个带有React本机前端和Flask后端的应用程序.我设法通过本地网址从烧瓶服务器检索信息,但是我不知道如何在另一个方向进行通信并将信息发送到烧瓶服务器.我需要与后端进行通信,并将用户将提供的信息发送给应用程序.我使用的是Android模拟器(Android Studio).
I'm developing an application with a react native frontend and a flask backend. I managed to retrieve information from the flask server via a local url but I don't know how to communicate in the other direction and send information to the flask server. I need to communicate with the backend and send the information that the user will provide to the application. I work with an android emulator (Android Studio).
我做了什么:
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
const serverUrl = "http://10.0.2.2:5000/data"
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
information: null,
};
}
componentDidMount() {
fetch(serverUrl)
.then((response) => response.json())
.then((data) => {
console.log(data);
this.setState({
information: data.data,
})
})
.catch((error) => console.log(error))
}
render() {
return (
<View style={styles.container}>
<Text>{this.state.information}</Text>
</View>
)
}
}
...
和
from flask import Flask
app = Flask(__name__)
@app.route('/data')
def get_data():
return {"data": "monument"}
if __name__ == '__main__':
app.run(debug=True)
推荐答案
我解决了这个问题:
req = {}
@app.route('/send', methods=['GET', 'POST'])
def get_data():
global req
if request.method == 'POST':
req = request.get_json()
print(req)
return req
else:
return "Data received in server"
这篇关于如何与Flask服务器(后端)通信以从React Native前端发送信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文