Encountered a 404 error while utilizing the Java - Angular web service

Encountering an error 404 in Firebug when attempting to send an object from Angular to a Java controller using JSON. While the backend in Java is able to receive the message, Angular is unable to find the specified path. Consequently, there is an issue with responding back to Angular.

This is the JSON data being sent:

{"title":"sdtgb","authors":[{"author_id":60,"author":"Brandon Sanderson"}],"genres":[{"genre_id":14,"genre":"Satyra"}],"description":"sdtb","path_image":"19674.png"}

Here is the Java controller code snippet that processes the incoming messages:

@SuppressWarnings("finally")
    @RequestMapping(value = "/rest/book", method = RequestMethod.POST)
    public MessageDTO addNewBook(@RequestBody BookDTO newBook) {
       // Code logic here
    }

The path where Angular sends the message and the associated error from Firebug are as follows:

"NetworkError: 404 Not Found - http://localhost:8080/engineering-project-web/rest/book"

Definition of BookDTO class:

public class BookDTO implements Serializable{
   // Class variables and methods defined here
}

JavaScript snippet:

Controller section:

// JavaScript code for handling book addition
var book = {
           // Content definition here
        }

// Calls a function to add a new book
NewBookFct.addNewBook(book)
                .then( function(resolve){
                    if(resolve.check){
                        alert("Book has been added.");
                    }else{
                        alert(resolve.description);
                    }
                }, function(reason){
                    console.log(reason);
                });

Service segment:

// JavaScript service function to incorporate adding a new book
service.addNewBook = function(book){
          // Logic implementation here
    }

Answer №1

If you find yourself running your Angular app on localhost:3000 while the Java Web is on localhost:8080, you may encounter issues with making cross-site requests due to security restrictions.

To resolve this, you will need to configure CORS on your web application. This can be easily accomplished by incorporating a library and adjusting your web.xml settings. For more information, refer to:

If you utilize Maven, simply include the following dependency:

<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>2.5</version>
</dependency>

Subsequently, insert a configuration like the one below into your web.xml file:

<filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    <init-param>
        <param-name>cors.supportedMethods</param-name>
        <param-value>GET, POST, HEAD, PUT, DELETE, OPTIONS</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/api/*</url-pattern>
</filter-mapping>

In the configurations provided above, CORS is activated for GET, POST, HEAD, PUT, DELETE, and OPTIONS requests targeting any URL within the /api route of your web application.

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

Utilize the reference of a variable in a separate class

I am trying to move the list of operators from my activity spinner into another class and then reference it in the spinner adapter. Can someone help me with how to do this? Below is the list of Operators: public class COperatorData { protected COperatorS ...

Functionality of multiple sliders

Is there a more efficient way to handle the fading in and out of sections on a slider? I currently have separate functions for each section, but I'd like to simplify it so that I only need one function for all 100 sections. Any suggestions? $(&apos ...

What is the best way to retrieve user data for showcasing in a post feed using firebase's storage capabilities?

I'm currently developing a forum-style platform where users can share content that will appear on a universal feed. I intend to include user details in the posts (such as photoURL and displayName) similar to how it is done on Twitter. For this projec ...

Tips for handling 429 errors while using axios in a react native application

My React Native app is connected to a MongoDB database using Express and Node.js, with Axios handling client-server communication. The app frequently exchanges data with the database, sometimes up to 4 requests per second when in use. While everything wor ...

Is it possible to update the event parameters with every click?

Is there a way to dynamically add a Select box for selecting a condition each time the "add" button is clicked? For example, when the add button is clicked, I would like the following elements to be continuously added: https://i.stack.imgur.com/6bad2.png ...

Android: Combining File Upload with JSON/PHP String Transmission

As someone who is not well-versed in PHP, I have gathered information from various sources on the Internet and from questions on this platform. My current task involves sending a file to a WAMP server using a PHP Script, along with sending a String to crea ...

JavaScript rearrange array elements

Currently, I'm attempting to move the values of an array over by a random amount. For instance: var array = [1,2,3,4]; var shiftAmount = 1; The goal is to shift the array so that it looks like [4,1,2,3] ...

Ways to achieve outcomes from functions employing concatMap within rxjs?

When calling two functions, I make use of fn1 and fn2. To execute them one after the other, I utilize concatMap. I choose not to use exhaustMap and switchMap as they can result in nested "callback-hell". exhaustMap(() => fn1().pipe( swit ...

When the status is set to "Playing," the Discord Audio Player remains silent

So, I'm in the process of updating my Discord audio bot after Discord made changes to their bot API. Despite my best efforts, the bot is not producing any sound. Here's a snippet of the code that is causing trouble: const client = new Discord.Cl ...

Select elements from a PHP loop

As part of my school project, I am developing a basic webshop. Currently, I am using a while loop to display featured products on the homepage. However, I now need to implement a shopping cart functionality. After a user clicks the "add to cart" button, th ...

Movement and physics mechanics for players using Physi.js

As I work on a basic game using Three.js for rendering and Physijis for physics, my question can be applied to games in general. In games, players often display movement that appears disconnected from the physics engine. They can accelerate instantly and ...

Using npm-installed cesium for the web browser is a straightforward process that involves importing

Exciting news - Cesium is now available on npm! Once I've run npm install cesium in my project, all the codes are placed inside the node_modules folder. In the introductory hello world example of Cesium, it imports cesium similar to this: <script ...

Sometimes, JQuery struggles to set input values accurately

Exploring the single page app sample provided here, I have encountered some anomalies when attempting to manipulate input controls with JQuery under certain conditions. Below is the consistent HTML structure followed by the JavaScript snippets in question. ...

What is the best way to incorporate a for loop in order to create animations with anime.js?

I am currently working on implementing a for loop to create a page loader using JQuery along with the animation framework anime.js var testimonialElements = $(".loader-animation"); for(var i=0; i < Elements.length; i++){ var element = ...

Can JSON be parsed using Goutte?

When it comes to crawling websites, I have had no issues parsing HTML using Goutte. However, the problem arises when I try to retrieve JSON from a website and don't want to rely on file_get_contents() due to cookie management issues. Although I know ...

The Ajax POST request encounters failure, although it functions properly in the console

The ajax function below is encountering an error message with little information, simply stating "error": var form = formInfo; var url = $(formInfo).attr("action"); var data = $(formInfo).serialize(); $.ajax({ type: "post", url: ur ...

Unable to assign image src to a dynamically generated div

My current task involves setting the background URL of a dynamically created div in JavaScript, intended for use with the jQuery Orbit slider. Below is my approach: var content1 = null; $("#featured").html("<div id='content' style='&apos ...

Tips for generating a .csv document using data from an array?

I am currently utilizing a PHP class to validate email addresses in real-time. The PHP Script is functioning as expected: validating the emails and displaying the results on the same page by generating a <td> element for each validated email. Howeve ...

Unable to reach controller action with Ajax request

I've been encountering issues trying to make a Get request to hit the specified URL. Initially, I attempted inputting the URL parameter manually in a separate JS file, then transitioning all my JS to cshtml to test out Razor. However, I am still facin ...

Switch between pages within a reactjs application by utilizing react router

Greetings! I am currently diving into the world of reactjs and experimenting with navigation from one page to another by simply clicking on a link through react router. In my home.js file, I have listed out some interesting places and I aim to click on one ...