我正在和我的伙伴一起做一个项目,我们遇到了一个问题。我在 JavaScript 中有一个变量,我在 python 中需要它,所以我做了一个 Flask 和一个 post 请求,但当我运行它时,它给我带来了一个错误。我尝试过寻找其他地方并尝试其他解决方案,但似乎都不起作用,有人能看到我的错误吗?
Python:
@app.route('/receive-data', methods=['POST'])
def receive_data():
data = request.get_json() # Use request.get_json() to explicitly parse JSON
if data is None:
return jsonify({"error": "Invalid content type or empty payload"}), 400
variable = data.get('variable')
print(f"Received variable from JavaScript: {variable}")
return jsonify({"status": "success", "received_variable": variable})
if __name__ == '__main__':
app.run(debug=True)
Javascript:
var audioControls = document.getElementById("audioControls");
let currentSong = null
let audioElement = document.getElementById("audio");
audioElement.src = currentSong
let beatcheckbox = false
let clonecheckbox = false
document.getElementById("beatcb").addEventListener("change", function() {
var bcheckbox = document.getElementById("beatcb");
// Check if the checkbox is checked
if (bcheckbox.checked) {
console.log("beat checkbox is checked");
beatcheckbox = true
// The variable you want to send to Python
const myVariable = beatcheckbox;
// Send the variable using fetch
fetch('http://127.0.0.1:5000/receive-data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Charset': 'UTF-8',
'Accept': 'application/json'
},
body: JSON.stringify({ variable: myVariable })
})
.then(response => {
if (!response.ok) {
return response.text().then(text => { throw new Error(text) });
}
return response.json();
})
.then(data => {
console.log('Response from server:', data);
})
.catch((error) => {
console.error('Error:', error);
});
} else {
console.log("beat checkbox is not checked");
beatcheckbox = false
}
});
document.getElementById("clonecb").addEventListener("change", function() {
var clonecbox = document.getElementById("clonecb");
if (clonecbox.checked) {
console.log("clone checkbox is checked");
clonecheckbox = true
} else {
console.log("clone checkbox is not checked");
clonecheckbox = false
}
});
我尝试在标头中添加接受(这不起作用),在邮递员中查看,在邮递员中我看到接受标头未设置,内容类型设置为text/html。我已经查看了所有代码,唯一提到接收数据的点是在我给出的代码中。
我尝试添加force=true,但它现在产生了这个问题:发生错误:400错误请求:无法解码JSON对象:期望值:第1行第1列(字符0)
您需要通过将 CORS 标头添加到服务器的响应中来允许 Flask 后端响应来自前端的请求。
您必须将 Python 代码更新为以下内容:
from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/receive-data', methods=['POST'])
def receive_data():
data = request.get_json() # Use request.get_json() to explicitly parse JSON
if data is None:
return jsonify({"error": "Invalid content type or empty payload"}), 400
variable = data.get('variable')
print(f"Received variable from JavaScript: {variable}")
return jsonify({"status": "success", "received_variable": variable})
if __name__ == '__main__':
app.run(debug=True)
让我知道这是否有效