I have created REST GET API using python Flask and it's code is below
app = Flask(__name__)
@app.route("/youtube")
def firstGetAPI():
try:
url = request.args.get('url')
print(f'URL is {url}')
res = "Success"
response = flask.Response(res)
response.headers.set('Access-Control-Allow-Origin', '*')
response.headers.set('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
return response, 200
except Exception as e:
response = {"status":"Fail", "message":str(e)}
return json.dumps(response)
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True, port=8080)
Now on Frontend side the Flutter code is below
child: ElevatedButton(
child: const Text('Download'),
onPressed: () async {
var header = {
'Access-Control-Allow-Origin': '*',
"Accept": "application/json"
};
var url = Uri.parse(
'http://192.168.2.237:8080/youtube?url=www.google.com');
print('URL is : ${url}');
var response = await http.get(url, headers: header);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
},
),
I have run this on Chrome Browser but I am always getting an error like below
URL is : http://192.168.2.237:8080/youtube?url=www.google.com
:49831/#/:1 Access to XMLHttpRequest at 'http://192.168.2.237:8080/youtube?url=www.google.com'
from origin 'http://localhost:49831' has been blocked by CORS policy: Response to preflight
request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
browser_client.dart:74 GET http://192.168.2.237:8080/youtube?url=www.google.com net::ERR_FAILED
Sorry as I have no idea if this is problem with Python or Flutter, I have combined both code over here, Thanks
CodePudding user response:
1st option
1- Go to flutter\bin\cache and remove a file named: flutter_tools.*
2- Go to flutter\packages\flutter_tools\lib\src\web and open the file chrome.dart.
3- Find '--disable-extensions'
4- Add '--disable-web-security'
2nd option
add header in python code header('Access-Control-Allow-Origin', '*')