I am having issues with making a simple fetch call using React to my Flask backend. I am using the componentDidMount lifecycle but keeps receiving a CORS issue. I have tried using CORS from flask_cors but still cannot get it. Help!
I have also tried adding proxy with the url to the backend in my package.json but still did not help.
React:
class App extends Component {
state = {
flights: []
}
componentDidMount(){
fetch('http://localhost:5000/flights')
.then(res => console.log(res))
.catch(err => console.log(err))
}
flask:
from flask_cors import CORS, cross_origin
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
import json
import random
import string
def get_confirmation_number():
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))
def flights(request):
with open('flights.json') as f:
content = json.loads(f.read())
return content
def book(request):
if random.randint(0,100) < 20:
return {
"success": False,
"message": "This flight is full."
}
else:
errors = []
try:
if 'first_name' not in request.json:
errors.append({
"field": "first_name",
"error": "is_required",
})
if 'last_name' not in request.json:
errors.append({
"field": "last_name",
"error": "is_required",
})
except:
errors.append({
"field": "all",
"error": "empty_request"
})
if not errors:
return {
"success": True,
"confirmation": get_confirmation_number()
}
else:
return {
"success": False,
"message": "You did not pass a valid request.",
"errors": errors,
}
if __name__ == '__main__':
with Configurator() as config:
config.add_route('flights', '/flights')
config.add_view(
flights, route_name='flights', renderer='json'
)
config.add_route('book', '/book')
config.add_view(
book, route_name='book', renderer='json'
)
app = config.make_wsgi_app()
CORS(app)
print('Servers on http://0.0.0.0:5000')
server = make_server('0.0.0.0', 5000, app)
server.serve_forever()
Ideally I would like to solve this on the front end and not have to use flask_cors, but if it is necessary I am open to that as well.
I got the same issue with the same stack but use CORS(app) solve this. It's probably a problem with make_wsgi_app()
You can try this:
server = make_server('0.0.0.0', 5000, app)
CORS(server)
server.serve_forever()