Resolved [Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported] что делать?

Простой код, не работает добавление элемента. В datatable данные выводятся. Через Postman добавляются! (например)

  {     
        "name": "name",
        "inventoryNumber": "оф-1111",
        "description": "description",
        "company": "company",      
        "responsiblePerson": "responsible_person",
        "typeOf": "OTHER"
    }

Ответ 201, и id нового элемента. Через ajax не добавляются. LOG

2022-10-06 17:46:22.105  WARN 16608 --- [nio-8081-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : 
Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]

В браузере:

timestamp   "2022-10-06T14:46:22.110+00:00"
status  415
error   "Unsupported Media Type"
path    "/api/equipments"

Если добавить в js

    dataType : "JSON",
    contentType: "application/json",

то в браузере ошибка

timestamp   "2022-10-06T15:02:09.096+00:00"
status  400
error   "Bad Request"
path    "/api/equipments"

JS файл it.equipments.js

function save() {
    $.ajax({
        type: "POST",
        url: ctx.ajaxUrl,                 
        //contentType: "application/json",
        //dataType: "json",
        //contentType:"application/json; charset=utf-8",
        //data: JSON.stringify(form.serialize() )
        data: form.serialize()
    }).done(function () {
        //const modal = new bootstrap.Modal(document.querySelector('#editRow'));
        modal.hide();
        //$("#editRow").modal("hide");
        ctx.updateTable();
        successNoty("common.saved");
    });
}

контроллер EquipmentRestController

@RequestMapping(value = EquipmentRestController.REST_URL, produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
//@RequestMapping(value = EquipmentRestController.REST_URL)
@Slf4j
@AllArgsConstructor
public class EquipmentRestController {
    static final String REST_URL = "/api/equipments";

    private final EquipmentService service;

    @GetMapping("")
    public List<Equipment> getAll() {
        log.info("getAll equipments");
        return service.getAll();
    }


    @GetMapping("/{id}")
    public ResponseEntity<Equipment> get(@PathVariable int id) {
        log.info("get equipment №{} ", id);
        return service.getById(id);
    }


    //@PostMapping( consumes = "application/json")
    //public ResponseEntity<Equipment> create(@Valid @RequestBody Equipment equipment) {
    //@PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @PostMapping()
    public ResponseEntity<Equipment> create(@RequestBody Equipment equipment) {
        //int userId = authUser.id();
        log.info("create {}", equipment);
        //checkNew(equipment);
        Equipment created = service.save(equipment);
        URI uriOfNewResource = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path(REST_URL + "/{id}")
                .buildAndExpand(created.getId()).toUri();
        return ResponseEntity.created(uriOfNewResource).body(created);
    }    
       
}

Модальное окно с данными:

<%--Модальное окно--%>
<div class="modal fade" tabindex="-1" id="editRow">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modalTitle"></h4>
                <button type="button" class="btn-close" data-bs-dismiss="modal" onclick="closeNoty()"></button>
            </div>
            <div class="modal-body">
                <form id="detailsForm">    
                    <%--<input type="hidden" id="id" name="id">--%>
                    <input id="id" name="id">

                    <div class="form-group">
                        <label for="name" class="col-form-label">Модель</label>
                        <input class="form-control" id="name" name="name"
                               placeholder="name">
                    </div>   

                    <div class="form-group">
                        <label for="description" class="col-form-label">description</label>
                        <input type="text" class="form-control" id="description" name="description"
                               placeholder="description">
                    </div>

                        <div class="form-group">
                        <label for="inventoryNumber" class="col-form-label">inventoryNumber</label>
                        <input type="text" class="form-control" id="inventoryNumber" name="inventoryNumber"
                               placeholder="inventoryNumber">
                    </div>

                        <div class="form-group">
                            <label for="company" class="col-form-label">company</label>
                            <input type="text" class="form-control" id="company" name="company"
                                   placeholder="company">
                        </div>

                        <div class="form-group">
                            <label for="responsiblePerson" class="col-form-label">Ответственный</label>
                            <input type="text" class="form-control" id="responsiblePerson" name="responsiblePerson"
                                   placeholder="responsiblePerson">
                        </div>

                        <div class="form-group">
                            <label for="typeOf" class="col-form-label">typeOf</label>
                            <input type="text" class="form-control" id="typeOf" name="typeOf"
                                   placeholder="typeOf">
                        </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="closeNoty()">
                    <span class="fa fa-close"></span>Отмена
                </button>

                <button type="button" class="btn btn-primary" onclick="save()">
                    <span class="fa fa-check"></span>
                    save
                </button>
            </div>
        </div>
    </div>
</div>

Исходник на git GIT

Подскажите, что делать?


Ответы (1 шт):

Автор решения: Денис

Получается ошибка была в использовании Controller (в программе их пока два EquipmentUIController, EquipmentRestController) . С одним из них и работал без ошибок Postman (Rest). Для добавления через ajax надо было в EquipmentUIController добавить запись, например так:

@PostMapping
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void createOrUpdate( Equipment equipment) {
        log.info("EquipmentUIController createOrUpdate");
        if (equipment.isNew()) {
            create(equipment);
        } else {
            //update(equipment, equipment.getId());
        }
    }

И исправить JS файл it.equipments.js Заменив

/api/equipments

на

/profile/equipments

То есть обращение не к REST а к UI контроллеру.

Всем спасибо, за участие.

→ Ссылка