HTTP Error 0 - Response for preflight has invalid HTTP code 400

Hey!
I’ve been trying to request my API, but I keep getting HTTP error 0.
Upon looking in the logs, it give me the following:
Failed to load https://ua71u3gk76.execute-api.us-east-1.amazonaws.com/prod/buslineapi: Response for preflight has invalid HTTP status code 400

I’m pretty sure the error isn’t in my end, because when I do a curl request it works perfectly, and the API’s log reveal that it received a OPTIONS request instead of a POST request.

It also works perfectly when I do a GET request.

Please see my code below:
url = "https://ua71u3gk76.execute-api.us-east-1.amazonaws.com/prod/buslineapi"
body = {"stop_area": "stop_area:WHT:SA:CTP102462", "line": "route:WHT:32-Whistler"}
r = anvil.http.request(url,method="POST",json=True,data=body)

Thanks in advance

I’ve solved it.
I needed a response for an OPTIONS request in my API, and I needed to enable CORS, and add headers to the response on my API.

1 Like

Yep, that’s right! HttpError code 0 happens when you make a request from the browser (ie from Form code), and the browser disallows the request.

This is usually for one of two reasons:

  1. You’re requesting an unencrypted (http://) URL. All Anvil apps are served over encrypted links (HTTPS), so the browser won’t let you make unencrypted requests.

  2. The URL doesn’t obey the cross-origin rules. (Needs to respond to an OPTIONS request, have the right CORS headers, etc.)

There are two possible ways to respond:

  1. Make the URL behave correctly. (Serve it over HTTPS, give it the right CORS headers, etc. This will require some expertise with web serving, and requires you to control the URL you are requesting. You’ll need to open up your browser’s developer console in order to work out what precisely it is objecting to.)

  2. Make the request from a server module instead. Server modules don’t run in the web browser, so they don’t have any of the browser’s limitations.

Hope that helps!