javascript - Python Flask 出现 AJAX CORS 错误

标签 javascript python-2.7 flask

通过我的 Python Flask 应用程序,我想通过 Javascript 执行以下操作。

<script>
    $.ajax({
        url: "http://localhost:5000/card_clf",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify({"line": "가나다라.\tstc"}),
        success: function(res) {
            document.getElementById("div01").innerHTML = res;
        }
    });
</script>

但是,我遇到了一个错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/card_clf. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

最佳答案

我通过将以下代码中的“@app.after_request”部分添加到我的 Python Flask 应用程序中解决了这个问题。

from flask import Flask, request


app = Flask(__name__)


@app.route('/card_clf', methods=["POST"])
def greet():
    ...
    return response


@app.after_request
def add_headers(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    return response

关于javascript - Python Flask 出现 AJAX CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35306326/

相关文章:

python - Python如何替换多个字符串中的一个子串?

python - 在 Python 中使用 ElementTree 解析具有命名空间的 XML

python - 检查目录是否已经创建python

jquery - 使用ajax和flask来更新表

mysql - 当 SQLAlchemy 并发更新同一条记录时出了什么问题?

html - 来自不同设备的 flask 访问

javascript - 简单的 Kendo 网格单元格模板以无包装方式显示单元格数据,结尾为 '...' 和一个按钮

javascript - 将 JSON 对象推送到数组

javascript - 为什么是 "TypeError: f is not a function"?

javascript - iOS 6 - 有没有办法清除缓存的 ajax POST 请求以添加到主屏幕的 Web 应用程序?