CORS strange behaviour with trailing slash using React and Flask API

Viewed 1130

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,

1 Answers

/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

Related