I'm making an API with FastAPI, and the frontend is made with next.js, so when the nextjs application makes a post request to the API, it should return the data normally with no problem, but it keeps giving a CORS error, the cors in the API are:
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
and the cors error is
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://jc-api-test.herokuapp.com/users/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 500.
CodePudding user response:
Since the error code is 500 - this is an internal server error, meaning something is wrong with your code. When a 500 error happens, the CORSMiddleware doesn't get to add any headers to the response, since an exception is thrown and regular request processing no longer happens.
Fix the error first (the log will show you what actually happens), then start debugging any CORS issues after that (see the other answers).
CodePudding user response:
The client should be making an OPTIONS request before the POST. It's the server's response to that initial call that needs to have the Acces-Control-Allow-Origin header. Then also that header's value must match the client (that heroku domain in your error message). Make sure your server is handling that OPTIONS correctly and it should work.
CodePudding user response:
Your allow_credentials
setting breaks the setting.
As stated in FastAPI documentation, if allow_credentials
is True
, you must define some origins instead of ['*']
:
allow_credentials - Indicate that cookies should be supported for cross-origin requests. Defaults to False. Also, allow_origins cannot be set to ['*'] for credentials to be allowed, origins must be specified.