corydolphin / flask-cors

Cross Origin Resource Sharing ( CORS ) support for Flask
https://flask-cors.readthedocs.io/en/latest/index.html
MIT License
884 stars 139 forks source link

CORS failure on invalid paths blocks 404 response #262

Open Rawk opened 4 years ago

Rawk commented 4 years ago

I want to show users of my webapp a "Resource not found" message when the requested path is not found (404) on the backend API.

To do that, the CORS preflight have to succeed (200 OK), so that the real request can give the 404 response.

Client use-case example:

fetch('https://api.example.com/path/not/found/on/server')
  .then(response => {
    const payload = await response.json()
    if (response.ok) {
      return { status: 'success', payload: payload }
    } else {
      // Never gets here!
      return { status: 'error', message: payload.message, httpStatus: response.status }
    }
  })
  .catch(e => {
    // Gets here with a not very helpful error message, and lost response.status
    // Chrome: "Failed to fetch"
    // Firefox: "NetworkError when attempting to fetch resource."
    return { status: 'error', message: e.toString() }
})

CORS preflight succeeding for unknown path would give:

HHK1 commented 3 years ago

Agree with that, actually posted a question on stack overflow on what should be the status code: https://stackoverflow.com/questions/64352697/should-a-server-implementing-cors-always-reply-with-a-2xx-code

nioncode commented 3 years ago

Fwiw, if you use a custom error handler, simply decorating it with @cross_origin() will make the OPTIONS preflight requests succeed with 200 and the actual request will fail with the response from your error handler, which can then be parsed by clients as usual.

That's how I implemented it in my backend after struggling with not receiving the correct error responses in javascript.

n1ngu commented 8 months ago

I think it would be awesome to test and document the approach described by @nioncode