I tried to connect HTML and python file, but i got error 405
HTML:
`
POST и GET запросы
body {
font-family: Arial, sans-serif;
margin: 20px;
}
#result {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
background-color: #f9f9f9;
}
Отправка POST и GET запросов
Отправить POST запрос
Отправить GET запрос
<div id="result"></div>
<script>
document
.getElementById("postButton")
.addEventListener("click", function () {
const inputText = document.getElementById("inputText").value;
fetch("/getpost", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ text: inputText }),
})
.then((response) => {
if (!response.ok) {
throw new Error(
"Не удалось выполнить запрос, статус: " + response.status
);
}
return response.json();
})
.then((data) => {
console.log("POST:", data);
document.getElementById("result").innerText =
"POST запрос отправлен: " + JSON.stringify(data);
})
.catch((error) => console.error("Ошибка:", error));
});
document
.getElementById("getButton")
.addEventListener("click", function () {
fetch("/getpost")
.then((response) => {
if (!response.ok) {
throw new Error(
"Не удалось выполнить запрос, статус: " + response.status
);
}
return response.json();
})
.then((data) => {
console.log("GET:", data);
document.getElementById("result").innerText =
JSON.stringify(data);
})
.catch((error) => console.error("Ошибка:", error));
});
</script>
`
PYTHON:
`from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/getpost', methods=['POST', 'GET']) # Измените URL на '/getpost'
def handle_requests():
if request.method == 'POST':
data = request.json
return jsonify({"message": "POST успешно получен", "data": data})
elif request.method == 'GET':
return jsonify({"message": "GET успешно выполнен"})
if name == ‘main‘:
app.run(debug=True)`
New contributor
user547259 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.