What I’m trying to do:
I am trying to create some authenticated API endpoints for my app that utilize POST requests to edit my database. These requests will be coming from other computers on the internet. I have been successfully able to get GET requests working, but even the simplest of post requests always give an HTTP 403 error.
What I’ve tried and what’s not working:
I have tried all combinations of enabling the ‘enable_cors’ and ‘cross_site_session’ parameters, and I have tried manually trying to add CORS headers via a wrapper function. Note that I have included logging inside the function to try and see if I am ever entering it, and I never see the debug log appear. This leads me to believe the request is getting blocked entirely somehow.
Code Sample:
# Here is an example endpoint that I have been testing with:
@anvil.server.http_endpoint("/test_post", methods=["POST"])
def test_post(**params):
logging.debug(f"Received POST request with params: {params}")
return {"status": "success", "params": params}
# Here is the example cors header wrapper I tried
def cors_enabled(func):
@wraps(func)
def wrapper(*args, **kwargs):
response = func(*args, **kwargs)
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
return response
return wrapper
# Here is some code I was using to test it, using python's request library
url = f"http://{my_url}/test_post"
data = {"key": "value"}
response = requests.post(url, json=data)
print(response)
print(response.headers)
print(response.text)
<Response [403]>
{'Content-Type': 'text/html; charset=utf-8', 'X-Xss-Protection': '1; mode=block', 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', 'Content-Length': '35', 'Server': 'http-kit', 'Date': 'Fri, 13 Dec 2024 00:29:36 GMT'}
<h1>Invalid anti-forgery token</h1>
I notice the Invalid anti-forgery token message, how can I solve that??