Home > Software engineering >  FastAPI rejecting POST request from javascript code but not from a 3rd party request application (in
FastAPI rejecting POST request from javascript code but not from a 3rd party request application (in

Time:03-10

When I use enter image description here

What should I do to get around this error?
Thanks in advance.

CodePudding user response:

It's and old issue, described here. You need Access-Control-Request-Method: POST header in your request.

CodePudding user response:

To start with, your code seems to be working just fine. The only part that had to be changed during testing it (locally) was the URL in fetch from /post/submit_post to (for instance) http://127.0.0.1:8000/post/submit_post, but I am assuming you already changed that using the domain name pointing to your app.

The 405 Method Not Allowed status code is not related to CORS. If POST was not included in the allow_methods list, the response status code would be 400 Bad Request (you could try removing it from the list to test it). From the reference above:

The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed response status code indicates that the server knows the request method, but the target resource doesn't support this method.

The server must generate an Allow header field in a 405 status code response. The field must contain a list of methods that the target resource currently supports.

Thus, the 405 status code indicates that the POST request was received and recognised by the server, but the server has rejected that specific HTTP method for that particular endpoint. Instead, the response you get back from the server (as shown in the screenshot you provided) shows that the /post/submit_post endpoint accepts requests using GET method.

Therefore, I would suggest you make sure that the decorator of the endpoint in the version you are running is defined as @app.post, as well as there is no other endpoint with the same path using @app.get. Additionally, make sure there is no any unintentional redirect happening inside the endpoint, as that would be another possible cause of that response status code. For future reference, when redirecting from a POST to GET reuest, the response status code has to change to 303, as shown here. Also, you could try allowing all HTTP methods with the wildcard * (i.e., allow_methods=['*']) and see how that works (even though it shouldn't be related to that). Lastly, this could also be related to the configurations of the hosting service you are running the application; thus, might be good to have a look into that as well.

  • Related