https://github.com/fernando24164/flask-cors-preflight
https://github.com/fernando24164/flask-cors-preflight
Last synced: 3 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/fernando24164/flask-cors-preflight
- Owner: fernando24164
- Created: 2021-07-11T17:10:21.000Z (almost 4 years ago)
- Default Branch: master
- Last Pushed: 2021-07-11T17:11:31.000Z (almost 4 years ago)
- Last Synced: 2025-01-28T02:44:23.199Z (5 months ago)
- Language: Python
- Homepage:
- Size: 1.95 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# CORS preflight example
## Table of Contents
- [About](#about)
- [Getting Started](#getting_started)
- [Usage](#usage)
- [Other interesting projects](#projects)Have you ever found problem with CORS preflight?
Do you want to know how to deal with it with Flask framework?
Well maybe, you are in the right place.Sometimes you deploy and REST API but suddenly when you test on develop environment you found something like
[CORS Preflight](https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request)### Prerequisites
Create a python virtualenv and install requirements.txt
```shell
virtualenv --python=/usr/bin/python3
```### Installing
Once created virtualenv install the requirements file
```shell
pip install -r requirements.txt
```To avoid this CORS preflight problem we need to implement an OPTIONS endpoint that return an Access-Control-Allow-Origin set to * to allow the request.
This OPTIONS endpoint is defined here
```python
from flask import Blueprint, Responsecat_options = Blueprint('cats', __name__)
@cat_options.route('/cats', methods=["OPTIONS"])
def cats():
return Response(status=200, headers=[('Access-Control-Allow-Origin', '*')])```
Launch Flask API
```shell
python src/wsgi.py
```How to test on local
```shell
curl \
--verbose \
--request OPTIONS \
http://localhost:5000/cats \
--header 'Origin: http://localhost' \
--header 'Access-Control-Request-Headers: Origin, Accept, Content-Type' \
--header 'Access-Control-Request-Method: GET'
```[flask-cors](https://github.com/corydolphin/flask-cors)