Error: The provided content type 'application/x-www-form-urlencoded;charset=UTF-8' is not supported in this context

I am currently attempting to create a post using JavaScript with AJAX to communicate with a Spring controller


    $("#crear").click(function () {
        var user = document.getElementById("user").value;
        var client = document.getElementById("client").value;
        var documents = document.getElementById("documents").value;
        if (user==null||client==null||documents==null){
            document.getElementById("error").innerHTML='FALTAN COSASsssssssssss';
            alert('Rellene todo los campos!')
        }
        const data={
            fecha_inicio:'A',
            id:'A',
            fecha_entrega:'A',
            usuario:{
                nombre:user
            },
            cliente: {
                nombre:client
            }
        }
        $.ajax({
            url: urlCrearAlta,
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: data,
            success: function(data) {
                // ...
            }

        });
        $.post(urlCrearAlta,JSON.stringify(data),function (data,satus){
            console.log('${data} and status is ${status}')
        });
        document.getElementById("error").innerHTML=user+client+documents;
    });

Furthermore, here is the Java code:

@RequestMapping("/altas")
@RestController
public class AltaRestController {

    private AltaController altaController;

    public AltaRestController(AltaController altaController) {
        this.altaController = altaController;
    }
@PostMapping("/create-alta")
    public void createAlta(@RequestBody AltaDTO altaDTO) {
        altaController.createAlta(altaDTO);
    }

I have encountered an issue with the error message: Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]

It appears that only using $.post triggers the request, while $.ajax does not send any requests

Answer №1

It appears that the issue lies in how the $.post method is being used. By default, jQuery uses the

application/x-www-form-urlencoded;charset=UTF-8
contentType for post requests, which may clash with the application/json required by the @RequestBody annotation on the backend. This mismatch results in the 415 status code and the exception being thrown.

The solution is simple - just ensure that the correct configurations are set for the .post method, like so:

$.post({
        url: urlCrearAlta,
        type: "POST",
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify(data)
    })
    .done((data, status) => {
          console.log(data, status);
          //do whatever you like with data and status
    });

It's worth noting that $.post is essentially a shorthand for $.ajax, so if one works and the other doesn't, it's likely an issue with how the request is configured or how the callback methods are being handled. The success function in the $.ajax request might be a potential culprit, so double-check that everything is correct there. Alternatively, consider using other callback methods like .done, .fail, and .always.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The proper way to utilize vue-material's tab router alongside vue-router

Exploring the usage of vue-material tabs in my Vue project for navigation, I discovered that the standard tabs provided already offer this functionality (). However, I'm struggling to integrate these tabs with the normal vue router in my current setup ...

Encountering issues with properly updating the Vuex store

Looking at my Vuex 2 store: const datastore = new Vuex.Store({ state: { socketcluster: { connection: false, channels: [] }, selected_offers: [] }, mutations: { addOffer: function(offer) { datastore.state.s ...

Is there a way to dynamically modify a website's default viewport settings in a mobile browser?

When viewing a website in Landscape mode, everything looks good. However, switching to Portrait mode displays the message "Screen size not supported." I decided to test this on my desktop browser and discovered that adjusting the initial-scale:1 to initial ...

The issue with Three.js responsive canvas is that it fails to properly adjust the size of the

I'm currently working on a threejs basic scene and attempting to create a responsive canvas for a full-screen experience. However, the mesh inside the scene is not resizing correctly as expected. Instead of remaining a cube, it distorts into a rectang ...

Implementing dynamic class bindings with Vue.js using v-for

I am currently using a v-for loop in Vue.js to create a list of items populated with data from an API. Here is an example of the items array: items: [ { foo: 'something', number: 60 }, { foo: 'anything', ...

Checking the security status of a PDF file in the web browser to determine if it

Within my platform, individuals have the ability to upload PDF files for others to access at a later time. In order to accommodate this functionality, I require that these PDFs are not secured or encrypted, and can be easily viewed by any user. To ensure ...

Tips for dynamically rendering a React component from an object

Looking to include an imported component with some props in my React code. Unable to find a solution on Stack Overflow for this specific format. Can someone provide guidance on how to achieve this? Thanks in advance. import { HomeIcon } from "../lib/i ...

How can I create a React component that is accessible and controllable from external sources?

Attempting to create a Dialog component using React and Material-UI. Currently, the component behaves like a traditional Material-UI dialog with a button inside the class that opens the dialog. However, I aim to achieve the same behavior as the default Ma ...

Is it possible to create a table containing names and scores solely using arrays and methods?

I've been on a quest to uncover the solution to this puzzling problem but have hit a dead end! Essentially, I am faced with the challenge of crafting a program where any number of players can participate in a guessing game by inputting their guesses a ...

Troubleshooting: Issues with jQuery Validate plugin's rules method in Javascript

I'm encountering an issue with a simple javascript file that is supposed to run the rules method, but it's not working as expected. I have confirmed that my custom javascript file is being rendered correctly since input masking is functioning pro ...

Angular Chart.js is throwing an error: "Uncaught SyntaxError: Cannot use import statement outside a module"

Upon opening the page, an error in the console related to Chart.js 4.2.1 is being displayed. Description of first image. Description of second image. Is it possible that this issue solely lies with Chart.js? How can it be resolved? To address the proble ...

Unable to utilize JavaScript from the imported AJAX page XMLHttpRequest

I have implemented a bit of AJAX functionality using XMLhttpRequest, where it replaces a div and functions as expected. However, I am facing difficulty in getting the JavaScript code in the included AJAX page to execute. Is there a way to run JavaScript f ...

Attempting to swap out a switch statement for an enum in Java

I am looking to refactor the following class by replacing a switch statement with an enum. public class FillTable { private static final int NAME_INDEX = 0; private static final int DESCRIPTION_INDEX = 1; private static final int CONTRIBUTION ...

Design a custom Bootstrap dropdown using an input[type="text"] element

After exploring the Bootstrap dropdown example here, I realized that for my particular scenario, it would be more beneficial to have an input field (type="text") instead of a button. This way, I can display the selected option from the dropdown. Is there ...

Retrieve the observable value and store it in a variable within my Angular 13 component

Incorporating Angular 13, my service contains the following observable: private _user = new BehaviorSubject<ApplicationUser | null>(null); user$ = this._user.asObservable(); The ApplicationUser model is defined as: export interface ...

Injecting variable styles into my VueJS component

I am currently working on developing a custom progress bar to visualize the percentage of completed tasks. The approach I am taking involves using v-bind:styles and passing {width: dynamicWidth + '%'} to regulate the progression of the bar. To ac ...

Can a new class be created by inheriting from an existing class while also adding a decorator to each field within the class?

In the following code snippet, I am showcasing a class that needs validation. My goal is to create a new class where each field has the @IsOptional() decorator applied. export class CreateCompanyDto { @Length(2, 150) name: string; @IsOptional( ...

Timeout error on Tomcat7 server in Eclipse

While running tomcat7 from Eclipse, I made sure that both Eclipse and Tomcat are using jdk-1.7.0. However, the server displays an error saying "timeout. Server took more than 45 seconds to boot". The issue arose when I changed the JDK for my project in Ec ...

Accessing the background page of a Chrome extension while it's in operation

I am in the process of developing my first chrome extension that allows youtube.com/tv to run in the background so it can be accessed easily on a phone or tablet. Everything is working fine, except for the fact that if I want to watch the video and not j ...

Limiting the length of parameters in an Angular directive

Is there a character limit for the parameter being sent to this directive? I'm encountering an issue with my code: header = JSON.stringify(header); columnObj = JSON.stringify(columnObj); $compile('<div column-filter-sort header=' + heade ...