I am now building a web application using a SolidJS frontend (http://localhost:3000) and FastAPI backend (http://localhost:8000).
However, due to the CORS issue, I cannot get the result at all even if the backend server sends response with status code 200.
Here is the following code for frontend.
...
axios({
method: 'post',
url: 'http://localhost:8000/login',
headers: { Accept: 'application/json' },
params: {
token: 'RANDOM_TOKEN_VALUE',
},
}).then((response) => {
console.log(response)
});
...
And here is the code for backend.
app = FastAPI()
origins = [
'http://localhost:3000'
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*'],
)
app.include_router(users.router)
...
@router.post('/login', response_model=CustomModel)
async def login(token, request: Request = None):
...
return response
When I check the developer tools in Chrome browser, the backend sent the correct response with status code 200, but it is blocked due to CORS policy. However, I allowed the frontend host in the FastAPI setting, I don't know what to do.
I also share the raw request and response header in the Chrome browser.
Request header:
POST /login?token=RANDOM_TOKEN_VALUE HTTP/1.1
Accept: application/json
Accept-Encoding: gzip, deflate, br
Accept-Language: ko,en-US;q=0.9,en;q=0.8
Connection: keep-alive
Content-Length: 0
DNT: 1
Host: localhost:8000
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36
sec-ch-ua: "Not)A;Brand";v="24", "Chromium";v="116"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Response header:
HTTP/1.1 200 OK
date: Wed, 23 Aug 2023 07:54:47 GMT
server: uvicorn
content-length: 184
content-type: application/json
access-control-allow-credentials: true
Since the backend server sends the correct response, I tried to add several options to the Axios function, but none of them worked.
- I tried to add "crossDomain: true" in the request header, but it does not work.
- I tried to add "Access-Control-Allow-Origin" in the request header, but it does not work.
- I tried to add both "withCredentials: true" and withCredentials: false" for the Axios, but none of them worked.