Calling Anvil HTTP endpoint from Javascript on other site

Ok, here’s an example.

https://anvil.works/build#clone:UCTPPYFRLQXABGHJ=JO2KQWQVV6LX7WTLGLU5UVPV
I have that app live at the following public URL : https://direct-unwieldy-desk.anvil.app/_/api/dave
You should be able to call that from anywhere (including your browser).

My endpoint looks like this :

@anvil.server.http_endpoint("/dave")
def dave_handler(**kwargs):
  r = anvil.server.HttpResponse()
  r.headers['Access-Control-Allow-Origin'] = '*'
  r.headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
  r.headers['Access-Control-Request-Method'] = '*'
  r.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  r.status = 200
  rnd = randint(1,100000)
  r.body = "Dave Called Successfully : " + str(rnd)
  app_tables.log.add_row(data="New "+str(rnd))
  
  return r

It inserts a line into the DB to indicate it’s doing something. Try calling it from your JS app as is (it should work), then try commenting out the cors bit and see if it fails.

If the CORS fails when commented out, you should still see a new row in the DB, proving that the endpoint runs even if CORS fails. So, if your endpoint is not running then something else is going wrong.

You can also test from here : https://resttesttest.com/ (just paste the API url, no need to set anything else).
This will fail without the CORS headers set in the response but work fine with them.

1 Like