What caused the server to return a 415 status error when trying to call the API post method?

I'm currently working on developing my own API using Spring Boot. Right now, it's set up to access external data from an air quality API.

Here is the CityInfo entity I have created:

@Entity
public class CityInfo{
    @Id
    private String id;
    private String name;


    public CityInfo(){

    }

    public CityInfo(String id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
.
.
.
}

The Rest Controller for handling CityInfo:

    @Autowired
    private CityInfoService cityInfoService;
    @Autowired
    private CityInfoRepository cityInfoRepository;

    @GetMapping("/CityInfo")
    public List<CityInfo> getAllCityInfo() {
        return cityInfoRepository.findAll();
    }

    @PostMapping ("/CityInfo")
    public void addCityInfo(@RequestBody CityInfo cityInfo) {
        cityInfoService.add(cityInfo);
    }

When making a POST request to "localhost:port/CityInfo" using Postman with {"id":"1","name":"London"}, everything works smoothly and the data is read in "/CityInfo".

However, when attempting to post data using JavaScript, I encounter Error 415 which indicates "415 Unsupported Media Type".

function postData(){
    let id = "31";
    let name = "CITYCITY"
    fetch('http://localhost:8084/CityInfo', {
        method: 'POST',
        body:JSON.stringify({"id":id,
                            "name":name})
    }).then((res) => res.text())
        .then((text)=>console.log("text:"+ text))
        .catch((err)=>console.log("err:" + err))
}
postData();

Upon checking the console, I see the following message: "Failed to load resource: the server responded with a status of 415 ()"

I suspect that the issue lies in the format of the JSON being sent, but I can't pinpoint the exact problem.

Any assistance would be greatly appreciated. Thank you.

Edit: Screenshot from Postman https://i.sstatic.net/JR3ej.png

function postData(){
    let id = "31";
    let name = "CITYCITY"
    fetch('http://localhost:8084/CityInfo', {
        method: 'POST',
        body:JSON.stringify({"id":id,
                            "name":name}),
        contentType: 'application/json',
        contentEncoding: 'gzip',
        contentEncoding: 'deflate',
        contentEncoding: 'br',
    }).then((res) => res.text())
        .then((text)=>console.log("text:"+ text))
        .catch((err)=>console.log("err:" + err))
}
postData()

Result: POST http://localhost:8084/CityInfo 415

Answer №1

To understand the significance of a 415 response, refer to the documentation provided here.

If you are encountering this error, it is possible that the Content-Type or Content-Encoding in your postData function is incorrect.

In any case, it is essential to verify what the endpoint expects and ensure that your request aligns with those specifications.

Answer №2

Essentially, my issue stemmed from incorrectly formatting a JSON document. While using Postman, I realized that the 'Content-Type' needed to be set to 'application/json'

Here is the revised JavaScript code snippet:

function sendData(){
    let id = "42";
    let city = "TOWNVILLE"
    fetch('http://localhost:8084/CityInfo', {
        method: 'POST',
        body:JSON.stringify({"id":id,
                            "city":city}),
        headers: {
            'Content-Type': 'application/json'
        }
    }).then((res) => res.text())
        .then((text)=>console.log("Response:"+ text))
        .catch((err)=>console.log("Error:" + err))
}
sendData()

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

Error in Prisma: Unable to retrieve data due to undefined properties (attempting to access 'findMany')

Recently, I've been working on a dashboard app using Prisma, Next.js, and supabase. Encountering an issue with the EventChart model in schema.prisma, I decided to create a new model called EventAreaChart. However, after migrating and attempting to ex ...

Sending a Set from a Node.js backend to the front end using socket.io

Why is it that when sending data from a Node.js backend to the frontend using socket.io, a set object is being converted into an empty object? Could this issue be related to JSON limitations, a bug in socket.io, or possibly a bug in Node.js? On the fronte ...

Switch it up on Radio Select by showcasing a variety of checkbox options

I am in search of a solution using either Javascript or jQuery. My requirement is that when a user selects an option from the radio buttons, a different set of checkboxes should be displayed. For example, if the user chooses "By Name", then the name check ...

Strange ASP.NET Redirection/Submission Problem

My code is enclosed in a try/catch block with a redirect to another page, but I'm encountering a problem. When a user clicks on a submit button, instead of redirecting to the intended page, the page simply refreshes and stays on the same page. This is ...

Encountered difficulties logging in with MongoDB and Node.js

I encountered an issue while attempting to authenticate a user using MongoDB and Node.js. Although no errors are thrown, the system fails to provide the expected data after the user logs in. Below is a breakdown of my code. server.js var port=8888; va ...

What is the best way to substitute </br> and <br/> with in a text?

Is there a way to replace </br> and <br/> with \n functionally? There seems to be varied responses to this query. Errors are often made when writing the break tag. The solutions for both types of breaks mentioned above are detailed below ...

Incorporate nested components on the fly within Angular 8

As I work on developing my angular 8 application, I find myself faced with the task of dynamically adding a nested component to the parent component upon clicking a button. Essentially, I am looking to create a functionality where the ADD button places the ...

Leveraging ng-change in AngularJS when utilizing the "Controller As" syntax

Attempting to steer clear of using $scope within my controller function, I have instead chosen to use var viewModel = this; employing the "controller as" viewModel syntax. The issue at hand is that while I can access data from a service, invoking functio ...

The AngularJS "multipart form" file upload is encountering an issue where undefined values are being sent to the server. As a result, the file cannot be

Here is the HTML code I am working with: <form > <input type="file" file-model="myFile"/> <button ng-click="uploadFile()">upload me</button> </form> Inside my controller, I have the following function: ...

Moving API information to a document

I'm curious about how to transfer the API data I have into my json file named "GameAPI.json". Inside the file, here's what I currently have: https://i.sstatic.net/H7taY.png (What I want): https://i.sstatic.net/Tsuzl.png "100" represents team 1, ...

Selecting multiple rows on a Lazily Loaded jQuery Datatable

Currently, I am utilizing a lazy loaded (Deferred) jQuery Datatable and attempting to implement multi-row selection. However, every time I switch to another page of the datatable, the selected rows from the previous page get cleared. // Here's how yo ...

Is my Node regex parser causing a memory leak?

After some testing, it appears that the code snippet provided causes Node to consume an excessive amount of RAM and eventually crash when memory runs out. However, upon adjusting the length of the found string from 13 to 12 characters, everything functio ...

The parsing module encountered an error due to an unexpected } token, causing a failure in

Can anyone help me figure out why this error keeps occurring? ERROR in ./login/loginController.js Module parse failed: /Users/leon/Projects/admin/login/loginController.js Line 66: Unexpected token } You may need an appropriate loader to handle this file t ...

Validate forms using jQuery with the power of ajax

Is there a way to effectively check for the existence of a username? I want to increment a variable called "form_error" if the username already exists. If "form_errors" is greater than 0, I need the code to stop and return false. However, when I use an Aj ...

"Receiving a 404 error when sending a POST request, but getting

When attempting to send a POST request, I encountered a 404 error response from the server. Strangely, when sending a GET request, I received a 200 response. I have experimented with different methods: $.ajax({ type:"POST", url: "script.php", ...

The anchorEl state in Material UI Popper is having trouble updating

I am currently facing an issue with the Material UI popper as the anchorEl state remains stuck at null. Although Material UI provides an example using a functional component, I am working with a class-based component where the logic is quite similar. I w ...

Is it a bug or a mystery that adding the second dependency causes an infinite loop in my custom React hook?

I've developed a basic React hook following common examples found in various guides and websites: import { useEffect, useState } from 'react'; import axios from 'axios'; export const useFetchData = (url, options, initialData) => ...

Is there a way to identify the font selected by the user's browser through Javascript?

Let's say the CSS on my web page for the body element looks like this: font-family: verdana, 'Liberation Sans', sans-serif; How can I determine if a user's browser is using 'Liberation Sans' font? I attempted to do something ...

Retrieve the ID of the element that is currently clicked and also retrieve the IDs of its children

Is there a method in Angular to retrieve the id of the currently clicked element and its child id? Similar to how it can be done in jQuery with the following code: $("a").click(function(){ var this_id = $(this).attr("id"); var child_id = $(this).f ...

Experiencing problems with CSS compatibility while transitioning from vanilla JavaScript to React

Currently, I am working on revamping the frontend of an app that was initially built with vanilla javascript and transitioning it to a React framework. However, I'm encountering some challenges with styling the HTML elements. Specifically, the textare ...