Пытаюсь через REST отправить id двух сущностей в контреллер добавления товара в корзину. У меня есть сам js-код:
$(document).ready(function () {
$("#buttonAddToCart").on("click", function (e) {
addToCart();
});
});
function addToCart() {
quantity = $("#quantity" + tourId).val();
url = contextPath + "cart/add/" + tourId + "/" + quantity;
$.ajax({
type: "POST",
url: url,
beforeSend: function (xhr) {
xhr.setRequestHeader(csrfHeaderName, csrfValue);
}
}).done(function (response) {
$("#modalTitle").text("Корзина");
$("#modalBody").text(response);
$("#cartModal").modal();
}).fail(function (request) {
$("#modalTitle").text("Корзина");
$("#modalBody").text("Произошла ошибка при добавлении тура в корзину\nСтатус: "+request.status");
$("#cartModal").modal();
});
}
Контроллер, который должен пронимать объекты сущностей и соединять их в другию таблицу
@RestController
public class ShoppingCartRestController {
@Autowired
private ShoppingCartService cartService;
@Autowired
private UserServiceImpl userService;
@PostMapping("/cart/add/{pid}/{qty}")
public String addTourToCart(@PathVariable("pid")Integer tourId,
@PathVariable("qty")Integer quantity,
@AuthenticationPrincipal Authentication authentication){
authentication = SecurityContextHolder.getContext().getAuthentication();
System.out.println("tourId"+tourId+"quantity"+quantity+"aut"+authentication.toString());
if(authentication==null||authentication instanceof AnonymousAuthenticationToken){
System.out.println("authentication is null");
return "Ваш нужно войти чтобы добавить этот тур в вашу корзину";
}
User user = userService.findUserByEmail(authentication.getName());
if(user==null) System.out.println("User is null");
Integer addedQuantity=cartService.addTour(tourId,quantity,user);
return addedQuantity+" шт. тура были добавлены в вашу корзину.";
}
}
И страница с кнопкой для отправки
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script type="text/javascript" th:src="@{/js/add_to_cart.js}"></script>
<script type="text/javascript" th:src="@{/js/quantity_control.js}"></script>
<meta name="product-id" data-th-content="${product.id}"/>
<title>[[${product.title}]] – Туристический сайт</title>
<csrf disabled="true"/>
<div class="container">
<img th:src="@{${product.imagePath}}" alt="Card image cap" width="320" height="200"/>
<h1 data-th-text="${product.title}"></h1>
<p>Дата: <span id="startTime" data-th-text="${product.startTime}"/> по
<span id="endTime" data-th-text="${product.endTime}"/></p>
<section id="description" data-th-text="${product.description}"></section>
<div th:replace="quantity_control::quantity_control(1,${product.id})">Количество</div>
<button type="submit" class="btn btn-danger" id="buttonAddToCart">Добавить в корзину</button>
</div>
<div th:replace="quantity_control::succes_modal">Modal</div>
<script type="text/javascript">
contextPath = "[[@{/}]]";
var csrfHeaderName = "[[${_csrf.parameterName}]]";
var csrfValue = "[[${_csrf.token}]]";
var tourId = "[[${product.id}]]";
</script>
При нажатии кнопки Получаю мадальное окно с ошибкой 405. В консоле:
А так понимаю, что ему не нравиться что-то в самом коде js-файла, поскольку до контроллера даже код не доходит. И есть проблемы в часте в объектом xhr.
А уже после выхода с профиля возникает GET
localhost:8080 net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 и вся главная страница пустая, пока вручную на зайдешь на странцу авторизацию. Но это я считаю, также связано с ajax-запросом
UPD Возможно, код не может получить запрос из-за того, что страница товара написана динамически, т.е. отображает информацию товара в зависимости на какой объект передается id товара, но я не уверен, что из-за этого.
@GetMapping("{productId}")
public ModelAndView product(@PathVariable Integer productId) {
return this.tourRepository.findById(productId)
.map(product -> new ModelAndView("home/tour",
Map.of("product", product), HttpStatus.OK))
.orElseGet(() -> new ModelAndView("errors/404",
Map.of("error", "Couldn't find a product"), HttpStatus.NOT_FOUND));
}
Прошу, помогите исправить проблему.