【问题标题】:Flask: issue remains even after enabling CORSFlask:即使在启用 CORS 后问题仍然存在
【发布时间】:2021-10-14 17:36:11
【问题描述】:

我有测试网站here。我已经在我的代码中启用了 CORS。

app = Flask (__name__,
            static_url_path='',
            static_folder='./')
cors = CORS(app,
            resources={r"/*":{"origins":"*"}},
            cors_allowed_origins="*",
            async_mode='threading'
            )
socketio = SocketIO(app)
socketio.run(app,port=5000, host='0.0.0.0')

这是一个示例响应:

@app.route('/getobsspecieslist', methods = ['GET'])
#@cross_origin(origin='localhost',headers=['Content- Type','Authorization'])
def resp_obsspecieslist():
    response = {}
    # Check if user sent a name at all
    query = """
    select t2.COMMONNAME
    from bird_observation_location_date_v3 t1
        left join ebird_info_dataset t2 on t2.bird_id = t1.bird_id
    group by t2.COMMONNAME
    order by t2.COMMONNAME asc
    """
    resp = []
    res = query_db(query)
    for row in res:
        resp += [{'name': row[0]}]
    response["result"] = resp
    response = jsonify(response)
    response.headers.add('Access-Control-Allow-Origin', '*')
    # Return the response in json format
    return response

仍然没有按预期工作。我环顾四周并尝试了多种建议,但均无济于事。请帮忙!

================================================ ================

进一步检查表明首先出现此错误:

Error  TypeError: NetworkError when attempting to fetch resource.    index.js:588:17

SetupSpeciesDropdown http://cocostraws.com/script/index.js:588
(Async: promise callback)
SetupSpeciesDropdown http://cocostraws.com/script/index.js:587
_onload http://cocostraws.com/script/index.js:18
onload http://cocostraws.com/script/index.js:2
(Async: EventHandlerNonNull)
<anonymous> http://cocostraws.com/script/index.js:2

来自这段代码:

function SetupSpeciesDropdown() {
    var url = "http://127.0.0.1:5000/getobsspecieslist"
    //var url = "http://www.cocostraws.com/getobsspecieslist"
    fetch(url, {mode: 'cors'}).then(res => res.json()).then(function(speciesList) {
        d3.select("select#dropdown")
            .selectAll('myOptions')
            .data(speciesList["result"])
            .enter()
            .append('option')
            .text(function (d) { return d["name"]; }) // text showed in the menu
            .attr("value", function (d) { return d["name"]; }); // corresponding value returned by the button

        d3.select("select#dropdown").on("change", function(d) {
                    // recover the option that has been chosen
                    selectedBird = d3.select(this).property("value");
                    // run the updateChart function with this selected option
                    LoadHeatMapData(selectedBird);
        });
        // Load the map corresponding to the first species in the list.
        selectedBird = speciesList["result"][0]["name"];
        LoadObsHeatMapData(speciesList["result"][0]["name"]);
    })
    .catch((error) => {
        console.error('Error ', error);   /* this is line 588 */
    });
};

第 588 行来自错误处理。它在较早的提取中失败。有人能指出我的错误吗?

【问题讨论】:

    标签: python flask flask-cors


    【解决方案1】:

    发现问题。它来自这两行:

    var url = "http://127.0.0.1:5000/getobsspecieslist"
    //var url = "http://www.cocostraws.com/getobsspecieslist"
    

    问题是我的网站前面没有www.。改成这样就可以解决问题了。

    var url = "http://cocostraws.com/getobsspecieslist"
    

    【讨论】:

      【解决方案2】:

      您的资源映射中的正则表达式不正确:r"/*" 匹配零个或多个正斜杠的字符串,您需要 r"/.*"flask_cors 需要 regex syntax(使用包 re),而不是 glob 语法。

      但是您可能还有其他问题。 cors_allowed_originsasync_mode 没有记录在案的关键字参数,您不需要 response.headers.add('Access-Control-Allow-Origin', '*') 行,这应该由扩展处理。

      最后,您需要能够传递凭据吗?如果是这样,请查看supports_credentials 选项的文档...并注意您不能将其与原点* 一起使用,这太不安全了。

      【讨论】:

      • 这两个关键字是从SocketIO误用的。我已经删除了它们。 resource 地图来自@porthunt 的回答here。我已经按照你的建议改了。标题添加也已被删除。还是不行。
      • 嗯,“没有按预期工作”没什么好说的。预期和观察到的行为是什么?套接字通信是否有效?响应发送什么标头?您使用身份验证吗?我建议您制作一个概念验证代码(只是上面的代码加上使其可运行所需的内容),并编辑您的问题以添加代码、响应标头和更详细的描述。
      • AJAX 请求失败,声明 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:5000/.... (Reason: CORS request did not succeed). 这是来自使用 Firefox 访问该站点时的控制台。
      • 使用 Firefox 控制台或curl 显示完整的响应标头。见上文。
      • 我已经用更新的信息更新了这个问题。
      【解决方案3】:

      我不知道您使用 CORS 标头的目的是什么,但如果您在前端 javascript 中为 AJAX 请求执行此操作,那么使用 CORS 标头肯定会起作用...请参阅W3schools documentation for AJAX

      【讨论】:

      • 嗨,Arjun,感谢您的参与。我不太关注。您建议对代码进行哪些更改?
      猜你喜欢
      • 2021-09-19
      • 1970-01-01
      • 2018-10-12
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2020-06-22
      相关资源
      最近更新 更多