CORS Woes (Again)

I really thought I’d gotten this CORS thing down pat.

I have an HTTP endpoint that was working fine. It starts off like this (based on some forum posts):

@anvil.server.http_endpoint("/order/total", methods=["POST", "OPTIONS"], enable_cors=True)
def total_order_api(**kw):
  # This allows JSON data to be sent to this endpoint
  if anvil.server.request.method == 'OPTIONS':
    r = anvil.server.HttpResponse()
    r.headers['access-control-allow-headers'] = 'Content-Type'
    return r

I was able to call that endpoint from some Javascript in a browser and get the right results.

Then I switched my app to use a custom domain. And now all of a sudden I’m getting a browser error:

'https://example.com/_/api/order/total' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

When I use a REST client to call the endpoint using the OPTIONS method directly, I see the right headers returned:

server	nginx
date	Tue, 08 Sep 2020 15:01:15 GMT
content-type	text/plain
content-length	0
access-control-allow-headers	Content-Type
access-control-allow-origin	*
strict-transport-security	max-age=31536000; includeSubDomains

Is this likely something I’ve broken? An artifact of switching to a custom domain? Something else entirely?

How frustrating! Off the top of my head, that looks like it should work - it looks like you’ve got the access-control-allow-origin header right there!

To confirm, are you hitting this endpoint from an anvil.http.request() in client code, or another app?

The next step is to open up Developer Tools in your browser, and look at the “network” tab. That will give you a way to see all the headers that are going to and from your HTTP endpoint - a screenshot of that will help us work out what’s going on! (Or, of course, you could give us a clone link for an app we can try that tries to POST to an endpoint and fails…)

Sigh, never mind.

Turns out some just-added exception handling code was ironically generating an error, and that error was causing a 500 response when called with real data. My tests with a REST client were not with real data, because I thought I was running into a problem with the CORS headers and just wanted to verify the headers. So those tests never got to the faulty code.

With the exception handling fixed, everything’s running smoothly again.

Sorry for the false report!