我已经尝试了互联网上所有的解决方案,但都失败了,我有一个Flask后端应用和react native前端应用。我有一个Flask后端应用和react native前端应用,Flask应用部署在Heroku上,React Native运行在localhost上。
从react native应用到heroku上的flask应用的POST请求失败。该错误发生在 访问XMLHttpRequest在'https:/authentication-heroku.herokuapp.com登录。'从源头开始'https:/localhost:19006。'已被CORS政策阻止。对飞行前请求的响应没有通过访问控制检查。它没有HTTP ok状态。
当两个应用程序都在localhost上时,其工作正常。但当flask在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://[email protected]/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()
似乎是一个安全问题,因为这两个应用程序不使用相同的协议(HTTPS),这是有道理的,他们在localhost上工作得很好,因为他们没有协议绑定,但现在flask rest 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来服务,看看除了这两种可能性之外是否还有其他的问题,享受吧!