Привет, ЛОР!
Написал функцию на js, от которой хочу следующее. Функция из другой функции получает строку и отправляет ее на бэкенд (в моем случае маршрут flask /cart/test_js
) и, в случае успеха, редиректит на этот адрес.
Полный код js:
// Function to send docsIds to flask backend (route /cart/test_js).
onst sendDocsIdsToFlask = () => {
const docsIds = getDocsIds();
// Create an AJAX request object
const xhr = new XMLHttpRequest();
// Set up the request headers and data
xhr.open("POST", "/cart/test_js", true);
xhr.setRequestHeader("Content-Type", "application/json");
// Convert the docsIds variable to a JSON string
const jsonData = JSON.stringify({ docsIds: docsIds });
// Send the AJAX request
xhr.send(jsonData);
// Handle the response from the server
xhr.onload = function () {
if (xhr.status === 200) {
// console.log("Success!");
window.location.href = "http://127.0.0.1:5000/cart/test_js";
} else {
console.error("Error:", xhr.statusText);
}
};
// Handle any errors that occur during the request
xhr.onerror = function () {
console.error("Error occurred:", xhr.statusText);
};
}
Код маршрута во flask:
@bp.route("/test_js", methods=["GET", "POST"])
@login_required
def test_js():
print(f"{request.get_json()=}")
return redirect(url_for('main.index'))
Это не работает. В консоли вижу ошибку
[Error] Failed to load resource: the server responded with a status of 415 (UNSUPPORTED MEDIA TYPE) (test_js, line 0)
Погуглив ошибку, нашел только, что это из-за того, что не указан тип отправляемых данных, хотя он у меня указан (application/json).
Вопросы: 1) как это пофиксить? 2) как при редиректе использовать не захардкоденные адреса, а динамичные из flask типа url_for(...)
?