Search code examples
reactjsnetlifypythonanywhere

How to connect a React frontend on Netlify to a Flask backend on PythonAnywhere


TLDR: React app interfaces properly with Flask API on PythonAnywhere when hosted locally but not when a static build is hosted on Netlify. Perhaps the proxy information is missing from the build?


EDIT 1: Here are the errors in the browser console: enter image description here


I've created a Flask API that pulls machine learning models from Amazon S3 and returns predictions on data input from POST requests. I've put this API on PythonAnywhere.

I've also created a React frontend which allows me to input data, submit it, and then receive the prediction. When I host this app locally, it behaves appropriately (i.e. connecting to the Flask app on PythonAnywhere, loading the models properly, and returning the predictions).

I've tried deploying a static build of the React app on Netlify. It behaves as expected, except for anything that requires interacting with the Flask App. I have a button for testing that simply calls the Flask app in a GET request, and even this is throwing a 404 error.

I checked the error and server logs on PythonAnywhere and see nothing. The only thing I can thik of is that my proxy which lists the domain of the PythonAnywhere app in my package.json file is for some reason unincluded in the build, but I don't know why this would be the case.

Has anyone else run into a similar issue or know how I can check to see if the proxy information is included in the static build? Thanks in advance!


Solution

  • Thanks to @Glenn for the help.

    Solution:

    1. I realized (embarrassingly late) that the requests were not going to the right address, as can be seen in the browser console error above. I was using a proxy during development, so the netlify app was calling itself rather than the pythonanywhere API. I simply went into my react code and edited the paths to pythonanywhere. E.g.
    onClick={ async () => {
            const response = await fetch("/get", {...}}
    

    became

    onClick={ async () => {
            const response = await fetch("https://username.pythonanywhere.com/get", {...}}
    
    1. As @Glenn mentioned, there may have been a CORS issue as well, so in my flask application I utilized flask_cors. I can't say for sure that this was necessary given that I didn't test removing it after the fetch addresses had changed, but I suspect that it is necessary.

    Hopefully this can help someone else