我正在构建一个web应用程序,其中前端使用Flutter,后端使用Python.

Access to XMLHttpRequest at 'http://127.0.0.1:8080/signal' from origin 'http://localhost:57765' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

下面是我用来发送GET和POST请求的Flutter 功能:

  Future<dynamic> sendResponse() async {
    final url = 'http://127.0.0.1:8080/signal';
    var data = {
      "signal": '8',
    };
    var header = {
      'Access-Control-Allow-Origin': '*',
      "Accept": "application/x-www-form-urlencoded, '*'"
    };


    http.Response response = await http.post(Uri.parse(url), body: data, headers: header);//http.post(Uri.parse(url), body: data, headers: header);//http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      print(json.decode(response.body));
      return jsonDecode(response.body);
      //print(json.decode(credentials.body));
    } else {
      print(response.statusCode);
      throw Exception('Failed to load Entry');
    }

   // var ResponseFromPython = await response.body;//jsonDecode(credentials.body);

   // return ResponseFromPython;
  }

下面是我使用Flask的Python后端代码:

   from flask import Flask,jsonify, request, make_response
   import json


   from flask_cors import CORS, cross_origin


   #declared an empty variable for reassignment
   response = ''

   app = Flask(__name__)

   #CORS(app, resources={r"/signal": {"origins": "*, http://localhost:59001"}}) 
   #http://localhost:52857
   #CORS(app, origins=['*'])
   app.config['CORS_HEADERS'] = ['Content-Type','Authorization']



   @app.route("/")
   def index():
    
    return "Congratulations, it worked"

   @app.route("/signal", methods = ['POST', 'GET']) #,
   @cross_origin(origins='http://localhost:57765',headers=['Content-Type','Authorization', 
   'application/x-www-form-urlencoded','*'], upports_credentials=True)# allow all origins all 
   methods.
   def multbytwo():
       """multiple signal by 2 just to test."""
       global response
       if (request.method=='POST'):
       # request.headers.add("Access-Control-Allow-Origin", "*")
           request_data = request.data #getting the response data
           request_data = json.loads(request_data.decode('utf-8')) #converting it from json to key 
   value pair
           comingSignal = request_data['signal']
           response = make_response(comingSignal, 201)#jsonify(comingSignal*2)
           response.headers.add('Access-Control-Allow-Origin', '*')
           response.headers.add('Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS')
           response.headers.add('Access-Control-Allow-Headers", "Content-Type, Authorization, X- 
  Requested-With')
           return response
       else:
           try:
        #scaler = request.args.get("signal")
               out = 9 * 2 
         
               response = jsonify(out)
               response.headers.add("Access-Control-Allow-Origin", "*") 
               return response #sending data back to your frontend app

           except ValueError:
               return "invalid input xyz"

   if __name__ == "__main__":
       app.run(host="127.0.0.1", port=8080, debug=True)

以下是我所做的故障排除步骤:

-Added some headers to the response itself to indicate that it accepts cross-origin

-Tried installing an extension in Chrome that by-passes the CORS check

我仍然不完全理解CORS的概念,但我try 了很多解决方案,但没有任何效果!请帮忙.

推荐答案

我终于弄明白发生了什么.

chrome.exe  --disable-site-isolation-trials --disable-web-security --user-data-dir="D:\anything"

This fired a separate chrome window that does not block cross-origin, we will call this the CORS free window. This allowed me to finally communicate with my python code and understand what is going on. You can see the

你可以看到chrome的默认设置甚至没有显示任何与响应相关的内容,只是显示了一个500代码错误.

I copied the localhost link and port and pasted them in my other CORS free chrome window The other CORS free chrome window showed helpful information: enter image description here

It was a simple JSON decoding error!我回到我的Flutter 代码,我更改了http post请求,在post主体上添加了jsonEncode函数:

http.Response response = await http.post(Uri.parse(url), body:jsonEncode(data), headers: header);

Now the post request returns a correct response on the default chrome settings. enter image description here It was just this CORS blocking the response completely that made me handi-capped.

Python相关问答推荐

使用matplotlib pcolormesh,如何停止从一行绘制的磁贴连接到上下行?

遵循轮廓中对象方向的计算线

使用from_pandas将GeDataFrame转换为polars失败,ArrowType错误:未传递numpy. dype对象

如何使用stride_tricks.as_strided逆转NumPy数组

在应用循环中间保存pandas DataFrame

如何处理嵌套的SON?

如何在python xsModel库中定义一个可选[December]字段,以产生受约束的SON模式

Python—从np.array中 Select 复杂的列子集

我如何根据前一个连续数字改变一串数字?

如何使用OpenGL使球体遵循Python中的八样路径?

循环浏览每个客户记录,以获取他们来自的第一个/最后一个渠道

Cython无法识别Numpy类型

当单元测试失败时,是否有一个惯例会抛出许多类似的错误消息?

BeautifulSoup-Screper有时运行得很好,很健壮--但有时它失败了::可能这里需要一些更多的异常处理?

如何求相邻对序列中元素 Select 的最小代价

GPT python SDK引入了大量开销/错误超时

如何将相同组的值添加到嵌套的Pandas Maprame的倒数第二个索引级别

简单 torch 模型测试:ModuleNotFoundError:没有名为';Ultralytics.yolo';

每次查询的流通股数量

为什么我的scipy.optimize.minimize(method=";newton-cg";)函数停留在局部最大值上?