4

I'm currently building an application with React and a Flask API and I got some CORS errors I don't understand :

I've got an endpoint like this :

@app.route('/home/', methods=['GET'])
def home():
    response = Response(
        json.dumps(
            get_data()
        ),
        mimetype='application/json'
    )
    response.headers.add("Access-Control-Allow-Origin", "*")
    return response

If I call this endpoint from react like this, everything works fine:

fetch('http://localhost:8080/home/')
            .then(res => res.json())
            .then((data) => {
                setData(data)
            })
            .catch(console.log)

However, if I set my route as '/home' in my Flask API (no trailing slash) and I call it using fetch('http://localhost:8080/home)' I got a CORS error: Access to fetch at 'http://localhost:8080/home' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Although it's not a big issue for my project, I would like to understand what this trailing slash change...

Thanks,

Nicolas Mauti
  • 506
  • 3
  • 13

1 Answers1

6

/home and /home/ are different routes to flask, but for routes with a trailing slash it will automatically do a redirect when accessing the route with a trailing slash.

So when your app accesses /home flask returns a redirect to /home/ but without the CORS-Header. This leads to the error you are seeing.

See also Flask Documentation

vinzenz
  • 669
  • 3
  • 14
  • I see but in the case that the flask route is '/home' and react fetches '/home' there is no need to redirect right? So why do I got an error in this scenario? – Nicolas Mauti Jun 02 '21 at 18:20
  • Honestly I don't know. Maybe you can check if your flask app is returning the correct responses by pressing F12 in your browser, then click on the "Network" tab. Then after visiting '/home' you can look at the http responses your app is sending. – vinzenz Jun 03 '21 at 06:39