无效的内容类型:application x www form-urlencoded

invalid content type: application x www form-urlencoded

当我将 RequestHeader 设置为 Content-type = "application/json" 时,它变为 'application/x-www-form-urlencoded' 并且出现不支持的媒体类型错误(无效的内容类型:application/x www 表单- urlencoded)

我的 RestController 代码:

 @PostMapping(value = "books/searchProcess/{pageNumber}")
@ResponseBody
public List<BookDto> bookSearchProcess(@RequestBody BookDto bookDto,
                                       @PathVariable(required = false) int pageNumber) {
    long totalPages = bookService.getTotalNumberOfPages(bookDto);
    if (totalPages == 0)
        return null;
    if (pageNumber > totalPages)
        pageNumber = (int) totalPages;
    return bookService.findMaxMatch(bookDto, pageNumber - 1, Integer.parseInt(env.getProperty("Page.Rows")));
}

我的 javascript 函数:

function sendToSearch(pageNumber) {
    let book = createJsonSearchObject();
    const request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (this.readyState === 4 && this.status === 200) {
            createResultTable(this.response);
        }
    };
    request.open("POST", "/admin/books/searchProcess/" + pageNumber, true);
    request.setRequestHeader("Content-type", "application/json");
    request.dataType = "json";
    request.responseType = "json";
    book = JSON.stringify(book);
    request.send(book);
}

  function createResultTable(books) {
    let table = document.createElement('table');
    table.setAttribute("id", "result-table");
    table.setAttribute("class", "table table-hover table table-bordered table-striped");
    let i;
    table.insertRow(0).outerHTML =
        `<tr class="header">
            <th>Book Name</th>
            <th>Author Name</th>
            <th>Author Family</th>
            <th>ISBN</th>
        </tr>`;
    for (i = 0; i < Object.keys(books).length; i++) {
        const book = books[i];
        table.insertRow(i + 1).outerHTML =
            `<tr>
                <td id="name` + i + `">` + book.name + `</td>
                <td id="author.name` + i + `">` + book.author.name + `</td>
                <td id="author.family` + i + `">` + book.author.family + `</td>
                <td id="isbn` + i + `">` + book.isbn + `</td>
            </tr>`;
    }
    const deleteBtn = document.createElement('button');
    deleteBtn.setAttribute("class", "btn btn-group btn-danger btn-delete");
    deleteBtn.setAttribute("id", "btn-delete");
    deleteBtn.setAttribute("onclick", "sendToDelete()");
    deleteBtn.appendChild(document.createTextNode("Delete Selected Items"));
    document.getElementById("search-result").append(table);
    document.getElementById("delete-btn").append(deleteBtn);
}

问题已解决。 就是我用了button标签发送用户请求,改成button类型的input就搞定了