I'm doing a web based project using flutter and flask. when I tried to use API to communicate between flutter and flask(note : I'm new to dealing with API's).
I got XML Http Request error, I tried all the solutions available but still no use and later found that installing flask-CORS module in flask can help resolve the issue. while importing flask-CORS module I faced with the above error.
Flask-CORS path and error
Flutter API code
CodePudding user response:
from flask import Flask,request,jsonify
from flask_cors import CORS,cross_origin
app = Flask(__name__)
CORS(app)
app.config['ENV'] = "development"
@app.route('/auth',methods=["POST"])
@cross_origin()
def login():
res=request.get_json()
em=res["email"]
pwd=res["password"]
print(em "\t" pwd)
return "success"
if __name__ == "__main__":
app.run(debug=True)
CodePudding user response:
https://flask-cors.readthedocs.io/en/latest/
Allow access to all apis that starts with /api from all origins.
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
or if you are testing from local try
cors = CORS(app, resources={r"/api/*": {"origins": ["http://localhost:5000/*"]}})
from flask import Flask,request,jsonify
from flask_cors import CORS,cross_origin
app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
app.config['ENV'] = "development"
@app.route('/auth',methods=["POST"])
@cross_origin()
def login():
res=request.get_json()
em=res["email"]
pwd=res["password"]
print(em "\t" pwd)
return "success"
if __name__ == "__main__":
app.run(debug=True)