How to communicate with a flask server (backend) to send it information from a react native frontend?

|▌冷眼眸甩不掉的悲伤 提交于 2020-06-29 04:45:09

问题


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).

What I did :

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>
            
        )
    }
}
...

and

from flask import Flask

app = Flask(__name__)

@app.route('/data')
def get_data():
    return {"data": "monument"}

if __name__ == '__main__':
    app.run(debug=True)

回答1:


You can do this with the fetch function by modifying it like so:

fetch("http://10.0.2.2:5000/send", {
  method: "post",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },

  //make sure to serialize your JSON body
  body: JSON.stringify({
    name: "John Doe",
    password: "john123"
  })
})
.then((response) => { 
    console.log(response);
   //do something here with the response from the flask server
});

You should also add another route with a method to handle this request in Flask. You can do it like so:

@app.route('/send', methods=['POST']) #GET requests will be blocked
def send():        # you can do something here with the data sent
    return "Data received in server successfully!"

Here's an article that provides more information on handling post requests in Flask.

Hope this helps :)




回答2:


Thank you Sahith Kurapati for your response.

I did it like this. But I got an error on the url page http://localhost:5000/send.

Internal Server Error : The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

Here's the flask code :

from flask import Flask, request

app = Flask(__name__)

@app.route('/data')
def send_data():
    return {"data": "monument"}

@app.route('/send', methods=['POST', 'GET'])
def get_data():
    if request.method == 'POST':
        return "Data received in server successfully!"

if __name__ == '__main__':
    app.debug = True
    app.run()

And here's the react native code :

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,
        };
    }

    _sendData() {
        fetch("http://10.0.2.2:5000/send", {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                name: "John Doe",
                password: "john123"
            })
        })
            .then((response) => { 
                console.log(response);
                console.log("ok");
            //do something here with the response from the flask server
            });
    }

    componentDidMount() {
        fetch(serverUrl)
            .then((response) => response.json())
            .then((data) => {
                console.log(data);
                this.setState({
                    information: data.data,
                });
                this._sendData();
            })
            .catch((error) => console.log(error))   
    }
    
    render() {
        return (
            <View style={styles.container}>
                <Text>{this.state.information}</Text>
            </View>
            
        )
    }
}
...



回答3:


I solved the problem :

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"


来源:https://stackoverflow.com/questions/62493824/how-to-communicate-with-a-flask-server-backend-to-send-it-information-from-a-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!