【发布时间】:2023-03-28 00:18:01
【问题描述】:
我已经尝试了互联网上所有可用的解决方案,但都失败了。我有一个 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()
【问题讨论】:
-
“我已经尝试了互联网上所有可用的解决方案,但都失败了”——这显然是错误的。夸张没有帮助。请在此处提问时尽量准确。见How to Ask。
-
试试httptoolkit.tech/will-it-cors看看它说了什么
标签: python react-native flask heroku cors