对Flask CORS问题做出反应

时间:2019-03-05 02:26:11

标签: ajax reactjs flask

我在使用React到Flask后端进行简单的提取调用时遇到问题。我正在使用componentDidMount生命周期,但一直收到CORS问题。我尝试从flask_cors使用CORS,但仍然无法获取它。救命!

我还尝试在package.json中将带有url的代理添加到后端,但是仍然没有帮助。

反应:

  class App extends Component {

  state = {
    flights: []
  }

  componentDidMount(){
    fetch('http://localhost:5000/flights')
    .then(res => console.log(res))
    .catch(err => console.log(err))
  }

烧瓶:

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()

理想情况下,我想在前端解决此问题,而不必使用flask_cors,但是如果有必要,我也愿意这样做。

1 个答案:

答案 0 :(得分:1)

我在相同的堆栈上遇到了相同的问题,但是使用CORS(app)解决了这个问题。 make_wsgi_app()

可能是一个问题

您可以尝试以下方法:

server = make_server('0.0.0.0', 5000, app)
CORS(server)
server.serve_forever()