Search code examples
javascriptpythonreactjsflaskvite

Error when trying to call a flask backend from a React project


When trying to connect my Flask backend to my Vite-React Project, I always get a multitude of errors trying to fetch the api provided. Erorr Log:

Access to fetch at "http://127.0.0.1:5000/members' from origin 'http://localhost:5 localhost/ :1 173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the
requested resource. If an opaque response serves your needs, set the request's mode to
'no-cors'
to fetch the resource with CORS disabled.

My App.jsx looks like :

import React, {useState, useEffect} from 'react'

function App() {

  const [data, setData] = useState([{}])

  useEffect(() => {

    fetch("http://127.0.0.1:5000/members").then(
      res => res.json()
    ).then(
      data => {
        setData(data)
        console.log(data)
      }
    )
  },[])

  return (
    <div>App</div>
  )
}

export default App

And my server.py looks like:

from flask import Flask

app =  Flask(__name__)

@app.route("/members")

def members():
    return {"members": ["member1", "member2", "member3"]}

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

I've tried including CORS in my flask server with CROS(app) to fix the fetch error, but it made no difference.


Solution

  • You are getting a Cross-origin resource sharing (CORS) related issue. You can read more about it following the link, but, in a nutshell, for an application to call an API that's not on the same domain, the API should allow it with a header.

    In your case, you could allow it using flask-cors, like so:

    pip install -U flask-cors
    
    from flask import Flask
    from flask_cors import CORS
    
    app =  Flask(__name__)
    CORS(app)
    
    @app.route("/members")
    def members():
        return {"members": ["member1", "member2", "member3"]}
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    Do not forget to restart your server after doing so.