Issue encountered while attempting to submit a POST request to a REST API, resulting in

I am currently working on developing a REST API in JavaEE and a client in ReactJS that interacts with this API.

When I use Postman to test the API, everything works perfectly fine. However, when I try to make POST requests using the fetch method in JavaScript from my client, I encounter a 415 error:

"Unsupported MediaType" is displayed in my browser's console.

For the API implementation, Jersey is used for request processing and Hibernate as ORM. I have included the genson dependency and verified that all works well with Postman.

Before sending any data, I also checked the result of JSON.stringify() and it appears correct.

In addition, every time I attempt to perform a POST request, I notice this error message in my server's console:

"A message body reader for Java class model.User, and Java type class model.User, and MIME media type application/octet-stream was not found."

Despite confirming that the correct headers are being sent and the content type is identified as 'application/json' by the browser, it seems like the API still does not accept or recognizes it as application/octet-stream mediatype.

Below is the code snippet where the fetch request is made:

signIn(){
    console.log(JSON.stringify(this.state));
    fetch('http://localhost:8080/P52/users', {
                method: 'POST',
                body: JSON.stringify(this.state),
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            }).then(res => {
                return res.json();
            }).catch(err=>err)
}

This is the method in the API that handles incoming data:

@POST
@Consumes(MediaType.APPLICATION_JSON)
public User createUser(User u){
    return UserController.createUser(u);
}

The controller simply creates a new instance of the User class to execute the code within the User model class :

public User(User u){
    this.id = u.getId();
    this.pseudo = u.getPseudo();
    this.firstname = u.getFirstname();
    this.lastname = u.getLastname();
    Session session = (Session)HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    session.save(this);
    session.getTransaction().commit();
    session.close();
}

If anyone has encountered this issue before or knows how to solve it, please share your insights so I can progress with this project. Your help would be greatly appreciated!

Answer №1

415 is an error code for Unsupported Media Type which can be found at this link

You can resolve this issue by making the following change:

@Consumes(MediaType.APPLICATION_JSON)

Change it to:

@Consumes(MediaType.APPLICATION_JSON_VALUE)

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

Tips for Troubleshooting External Evaluation Scripts

For a specific example, take a look at the haystack.js script from How Big is Your Haystack? I've been searching for a solution and it seems that using the //# sourceURL=name.js comment is the way to go. However, I am struggling with the process of a ...

How to retrieve element from templateUrl in AngularJS controller

I am facing a challenge in populating select(option) element inside a template html file from the controller. Although I have managed to do it successfully, I am unable to set a default value to avoid the initial empty option. Here is a snippet from the t ...

Enhancing webpage styles with AngularJS

Just starting out with AngularJS and eager to get the best approach to tackle this challenge. Describing my dilemma: I have an anchor element that, when clicked, needs to toggle between classes "show-all" and "hide-all" while also updating the styling of ...

What is the most efficient way to perform an array join in Node.js, akin to the speed of MongoDB's $

Looking to implement a $lookup function in Node.js similar to the $lookup aggregation in MongoDB. I have a solution in mind, but I'm unsure about its performance when dealing with larger arrays or bigger objects. let users = [ {userId: 1, name: ...

bespoke HTML elements and properties

I'm currently facing some difficulties and I am unsure of how challenging it can be. I have tried following various tutorials, including those on SO and YouTube, but they all provide different approaches leaving me stuck. My goal is to create a custo ...

How can I trigger a select tag change event in Jquery without any user interaction?

I'm currently facing a small hurdle. I have 3 cascading drop down lists, namely category, subcategory, and subsubcategory. The user picks a value from the category list, which then displays related values in the subcategory list. When the user changes ...

Guide on dividing a string by utilizing a lookahead assertion with dynamic delimiters

Recently, my English skills have become quite rusty, so I'll keep this brief. I am looking to split a string into substrings while keeping the delimiters as part of the respective substrings. The challenge lies in the varying delimiters. For example, ...

Utilizing Node.js and Express alongside EJS, iterating through objects and displaying them in a table

Today I embarked on my journey to learn Node.js and I am currently attempting to iterate through an object and display it in a table format. Within my router file: var obj = JSON.parse(`[{ "Name": "ArrowTower", "Class" ...

Wanting to utilize AJAX to send a post request and then retrieve the data on another page

Previously, I had this functionality working fine but it seems like something has changed now. I'm not able to pinpoint the exact issue as the code appears correct to me. It would be great if someone could take a look and identify the problem from a f ...

Sending an AJAX request to submit a form and receiving a response

I am in the process of developing a Rails application and I am seeking a way to submit a form using Ajax. This functionality is crucial as I want the form submission to occur without causing a full page reload. Initially, I tried using form_remote_tag but ...

Tips for retrieving the concealed input value from the div directly preceding

Is it possible for me to retrieve the hidden input value by clicking on the text "upload profile photo"? I don't have much experience in this area. <div> <input type="hidden" value='<?php echo $list['profil ...

Issue with firing the React-Redux action has been encountered

I am currently utilizing React along with react-redux, redux and redux-actions. Within my application, I have a specific action that is responsible for verifying the validity of the token stored in localStorage to ensure it is not expired. This action loo ...

Is there a way to make Firebase Cloud Functions utilize ESLint?

Is there a specific command to activate ESLint for my cloud functions? Just to provide some context, I executed firebase init and completed the setup process, but it ended up using ESLint instead of TSLint which was unexpected. After that, I ran firebase ...

Creating a switch case statement within a specific scope

How can I generate cases using $scope.type[i] (a JSON array from the database)? $scope.type = [{nomcarac: "phone"}, {nomcarac: "shoes"}]; $scope.getValuesList = function(item) { switch (item.type){ case 'phone': item.val ...

Create a distinct variable name for opening a modal within an *ngFor loop

I need help creating a unique variable called share within the *ngFor loop so that I can open a single modal. <li *ngFor="let gallery of galleries; let i = index"> <div class="gallery card" > <div class="sh ...

Generate dynamic modules components

Looking for a way to open modals globally and dynamically create components from any module? My project structure is organized with multiple modules, each containing modal components. Here's a simplified version: AppModule ---ModalOpenerServic ...

Switching from using fs.readFile to fs.createReadStream in Node.js

I have a dilemma regarding my code, which involves reading an image from a directory and sending it to index.html. My goal is to replace fs.readFile with fs.createReadStream, but I am struggling to figure out how to implement this change as I cannot seem ...

Combining dictionaries within a list by their main keys

I have a list containing multiple dictionaries with specific structures: dict1 = {'first': [{'att1': 'abc', 'att2': '123', 'att3': 'abc123'}, ...

What is the process for triggering a PHP function when a form element is clicked in a webpage?

Currently, I am trying to implement a jQuery colorbox on my webpage which appears over a <select> drop-down list. My goal is to trigger an AJAX call every time a new option is selected from the drop-down. Even though I have written the following cod ...

incorporating an HTML page into a div container

What is the best way to load an HTML page within a div element? I have been using the 'object' tag, but I'm unsure if it's the most efficient method. The HTML page is not external. Would using Dojo be a better solution for this situatio ...