1. 기본적인 해결
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
# ... your code ...
if __name__ == "__main__" :
app.run()
flask 에는 cors 문제를 해결할 수 있는 라이브러리가 있으니 이를 활용하면 된다.
2. 쿠키를 주고받을 때
하지만 쿠키를 주고 받을 때는 위와 같은 해결방식으로 해결이 안될 때도 있다.
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, origins=["https://localhost:3000", "outher_origin"], supports_credentials=True)
# CORS 관련 디버그 로그
logging.getLogger('flask_cors').level = logging.DEBUG
# ... your code ...
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'DELETE, GET, OPTIONS, POST, PUT')
return response
if __name__ == "__main__" :
app.run()
CORS 의 파라미터에 들어가는 supports_credentials 는
This allows cookies and credentials to be submitted across domains.
로 내 경우와 같이 쿠키까지 주고받을 경우 추가해야햔다. 기본값은 False이다.
CORS 관련 디버그 로그를 보면
Settings CORS headers: MultiDict([('Access-Control-Allow-Origin', 'https://localhost:3000'), ('Access-Control-Allow-Credentials', 'true'), ('Access-Control-Allow-Headers', 'authorization'), ('Access-Control-Allow-Methods', 'DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT'), ('Vary', 'Origin')])
이기에 헤더에 값을 추가하였다.
참고
https://flask-cors.corydolphin.com/en/latest/api.html
API Docs — Flask-Cors 3.0.10 documentation
Parameters: resources (dict, iterable or string) – The series of regular expression and (optionally) associated CORS options to be applied to the given resource path. If the argument is a dictionary, it’s keys must be regular expressions, and the value
flask-cors.corydolphin.com
# after_request 관련
https://flask.palletsprojects.com/en/2.2.x/api/?highlight=after_request#flask.Flask.after_request
API — Flask Documentation (2.2.x)
view_func (Optional[Union[Callable[[...], Union[Response, str, bytes, List[Any], Mapping[str, Any], Iterator[str], Iterator[bytes], Tuple[Union[Response, str, bytes, List[Any], Mapping[str, Any], Iterator[str], Iterator[bytes]], Union[Headers, Mapping[str,
flask.palletsprojects.com
'Framework > 플라스크(flask)' 카테고리의 다른 글
requests 에서 파라미터 가져오는 함수 (args/ arg.get) 차이 (0) | 2022.10.03 |
---|---|
flask , 폼테이터 업로드하기, 파일 업로드 (form-data upload, file upload) (0) | 2022.09.27 |
로컬에서 플라스크 2개 동시에 실행하기 (0) | 2022.09.14 |
flask_jwt_extended.exceptions error handling 에러처리 (0) | 2022.09.11 |
flask 에서 jwt 만료 안되게, 만료 시간(expires time) 설정하기 (0) | 2022.09.11 |