Search code examples
pythonreactjsflaskflask-restful

Post request from react to flask


I am trying to send a post request from react to flask using the following code:

function App() {

  const [currentTime, setCurrentTime] = useState(0);
  const [accessToken, setAccessToken] = useState(null);
  const clicked = 'clicked';
  

  useEffect(() => {
    fetch('/time').then(res => res.json()).then(data => {
      setCurrentTime(data.time);
    });
  }, []);


  useEffect(() => {
    // POST request using fetch inside useEffect React hook
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: 'React Hooks POST Request Example',action: 'clicked' })
    };
    var myParams = {
      data: requestOptions
    }
    fetch('http://127.0.0.1:5000/login', myParams)
        .then(response => response.json())
        .then(data => setAccessToken(data.access_token));

// empty dependency array means this effect will only run once (like componentDidMount in classes)
}, []);




  return (
    <div className="App">
      <div className="leftPane">
      
      <div className="joyStick"   >
        <Joystick  size={300} baseColor="gray" stickColor="black" ></Joystick>

        </div>
        <p>The current time is {currentTime}.</p>
        <p>The access token is {accessToken}.</p>


      
      </div>

And the flask code is

  from __future__ import print_function
from flask import Flask, jsonify, request
from flask_cors import CORS

import time
from flask import Flask
import sys


robotIP="10.7.4.109"
PORT=9559
app = Flask(__name__)

access_token='a'
action="d"


@app.route('/time')
def get_current_time():
    
    return {'time': time.time()}
    

@app.route('/login', methods=['POST'])
def nao():
    nao_json = request.get_json()



if not nao_json:
    return jsonify({'msg': 'Missing JSON'}), 400

action = nao_json.get('action')
access_token= action+'s'

print(access_token, file=sys.stderr)


return jsonify({'access_token': access_token}), 200

But every time I run both them both, I get the 'msg': 'Missing JSON' message I have defined and the data from react is never available in flask,even though the get request works.I am not sure what I am doing wrong here.


Solution

  • The problem actually is that this is a cross origin request which must be allowed by the server.

    Place this function on your Python code:

    @app.after_request
    def set_headers(response):
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers["Access-Control-Allow-Headers"] = "*"
        response.headers["Access-Control-Allow-Methods"] = "*"
        return response
    

    Note:

    • If react is served from the same server this won't be necessary.

    • You should set the value of these headers to be as strict as possible on production. The above example is too permissive.


    You could serve your React aplication from Flask, thus not requiring these headers to be set. You could use something like this to serve the main react file:

    @app.route('/', defaults={'path': ''})
    @app.route('/<string:path>')
    @app.route('/<path:path>')
    def index(path: str):
        current_app.logger.debug(path)
        return bp_main.send_static_file('path/to/dist/index.html')
    

    Where path/to/dist/index.html would be on the static folder.

    See more at: