5

Should non-2XX status code responses still include CORS specific headers such as Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Max-Age? Does that even make any sense for clients?

For example:

➜  api git:(master) ✗ curl -i http://127.0.0.1:9000/dfas
HTTP/1.1 404 Not Found
Connection: close
Server: Node.js v6.3.1
Cache-Control: no-cache, no-store
Access-Control-Max-Age: 300
Access-Control-Allow-Origin: *
Content-Type: application/json
Content-Length: 60
Date: Thu, 11 Aug 2016 22:58:33 GMT

{"code":"ResourceNotFound","message":"/dfas does not exist"}
Justin
  • 42,716
  • 77
  • 201
  • 296

1 Answers1

7

Yes it makes sense to have the server send CORS headers even with non-2xx responses. The reason is: without the CORS headers in the response, non-2xx response codes aren’t exposed to frontend code (through Fetch or XHR). The response codes may show up in the devtools console but without the CORS headers the only thing the frontend code will be able to determine programmatically is that an error occurred—but not the response code for the error.

So if you want frontend code to have the ability to do useful error handling based on the response code, the server should send CORS headers even in non-2xx responses.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
  • Thanks, exactly what I was thinking as well. – Justin Aug 11 '16 at 23:58
  • 1
    Yeah, sideshowbarker has the correct answer. CORS is just a way to tell the browser it is safe to share a response. And sharing error responses can be very useful for debugging. If you don't use CORS there it's the equivalent of the server just closing the connection. – Anne Aug 12 '16 at 04:23