flask-cors icon indicating copy to clipboard operation
flask-cors copied to clipboard

CORS failure on invalid paths blocks 404 response

Open Rawk opened this issue 4 years ago • 3 comments

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:

  • Better error handling on client. Possible to send payload/headers to client.
  • Better error messages when developing.
  • Same response with or without CORS, which depends on how the app is deployed.
  • Consistent with handling of 404s from valid paths.
  • Should CORS preflight always return 200? It is not so clear. For example see this https://stackoverflow.com/questions/46026409/what-are-proper-status-codes-for-cors-preflight-requests .

Rawk avatar Mar 27 '20 12:03 Rawk

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

HHK1 avatar Oct 14 '20 11:10 HHK1

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.

nioncode avatar Oct 14 '20 14:10 nioncode

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

n1ngu avatar Feb 04 '24 10:02 n1ngu