首页 > 解决方案 > FLASK,Heroku,React CORS 问题

问题描述

我已经尝试了互联网上所有可用的解决方案,但都失败了。我有一个 Flask 后端应用程序和反应原生前端应用程序。Flask 应用程序部署在 Heroku 上,React Native 运行在 localhost 上。

从反应本机应用程序到 heroku 上的烧瓶应用程序的 POST 请求失败。发生此错误 从源“ https://localhost:19006 ”访问“ https://authentication-heroku.herokuapp.com/login ”处的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。

当两个应用程序都在本地主机上时,它工作正常。但是当烧瓶在heroku上时,就会发生这个错误。下面是我的代码。

反应代码

let headers = {
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*"
        }

    let login_form = {
        email: email,
        password: password
    }
    axios.post('https://authentication-heroku.herokuapp.com/login', login_form, {headers: headers})
        .then(response => {
            console.log("response", response);
            if (response.statusText == "OK") {
                console.log("Ok");
                this.onLoginSuccess.bind(this);
                this.setState({ email: '',
                    password: '',
                    loading: false,
                    error: '',
                    loggedIn: true });
            } else {
                console.log("Not Ok");
                this.onLoginFail.bind(this);
                this.setState({ loggedIn: false,  error: 'Authentication Failed', password: '', email: '', loading: false });
            }
        })
        .catch(() => {
            this.onLoginFail.bind(this);
            this.setState({ loggedIn: false,  error: 'Authentication Failed', password: '', email: '', loading: false });
        });

烧瓶代码

from flask import Flask
from flask import request
from flask_cors import CORS, cross_origin
from flask_api import status
from flask_pymongo import PyMongo

app = Flask(__name__)
CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['MONGO_DBNAME'] = 'testdb'
app.config['MONGO_URI'] = 'mongodb+srv://username@development-xec6b.gcp.mongodb.net/testdb?retryWrites=true&w=majority'
mongo = PyMongo(app, resources={r"/login": {"origins": "https://localhost:19006"}})

@app.route('/login',methods=['POST'])
@cross_origin(origin='localhost',headers=['Content- Type','Authorization'])
def login():
    user = mongo.db.users
    email = request.json['email']
    password = request.json['password']
    email_exists = bool(user.find_one({'email': email}))
    pw_exists = bool(user.find_one({'password':password}))
    response = user.find_one({'email': email}).to_jon();
    response.headers.set('Access-Control-Allow-Origin', '*')
    response.headers.set('Access-Control-Allow-Methods', 'GET, POST')
    response.headers.set()
    if email_exists & pw_exists:
        return "Authenticated", status.HTTP_200_OK
    else:
        return "Record not found", status.HTTP_204_NO_CONTENT

if __name__ == '__main__':
    app.run()

标签: pythonreact-nativeflaskherokucors

解决方案


似乎是一个安全问题,因为这两个应用程序没有使用相同的协议(HTTPS),它们在 localhost 上运行良好是有道理的,因为它们没有协议绑定,但现在烧瓶休息 api 是在 https 连接上,我建议你打开 cors 策略pip install -U flask-cors并在您的应用程序中调用中间件

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

然后尝试将您的前端应用程序部署到非常简单的东西上,例如使用 nginx 代理或 express rest api 来提供服务,看看问题是否与这两种可能性不同,享受吧!


推荐阅读