通过我的 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/