gpt4 book ai didi

python - Flutter:请求的资源上不存在 'Access-Control-Allow-Origin' header

转载 作者:行者123 更新时间:2023-12-02 16:06:37 29 4
gpt4 key购买 nike

我已经使用 python Flask 创建了 REST GET API,它的代码如下

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)

现在在前端,Flutter 代码如下

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}');
},
),

我已经在 Chrome 浏览器上运行了这个,但我总是收到如下错误

     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

抱歉,我不知道这是 Python 还是 Flutter 的问题,我在这里合并了这两种代码,谢谢

最佳答案

第一个选项

1- 转到 flutter\bin\cache 并删除名为:flutter_tools 的文件。*

2- 转到 flutter\packages\flutter_tools\lib\src\web 并打开文件 chrome.dart。

3- 找到“--disable-extensions”

4- 添加“--disable-web-security”

第二个选项

在python代码header中添加header('Access-Control-Allow-Origin', '*')

Enable access control on simple HTTP server

关于python - Flutter:请求的资源上不存在 'Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69277199/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com