vue.js – axios로 데이터 request 시 CORS 오류 발생하는 경우

vue.js에서 backend 데이터를 얻기 위해 axios를 사용했다. backend는 FastAPI를 사용했는데 아래와 같은 오류가 나타났다.

Access to XMLHttpRequest at 'http://localhost:8000/translation' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Backend 로그 상에는 다음과 같은 오류 메시지가 출력된다.

INFO:     127.0.0.1:62005 - "OPTIONS /translation HTTP/1.1" 405 Method Not Allowed
INFO:     127.0.0.1:62039 - "OPTIONS /translation HTTP/1.1" 405 Method Not Allowed

구글링 해보니 FastAPI를 다음과 같이 구성하면 된다는 자료를 찾았다. (링크)

from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.responses import Response

app = FastAPI()


async def catch_exceptions_middleware(request: Request, call_next):
    try:
        return await call_next(request)
    except Exception:
        # you probably want some kind of logging here
        return Response("Internal server error", status_code=500)


app.middleware('http')(catch_exceptions_middleware)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get('/exception')
def get_with_exception():
    raise Exception('some exception')
    return {'test': 'test'}


uvicorn.run(app, host="0.0.0.0", port=8080)

Leave a Reply