Error 404: Angular 2 reports a "Not Found" for the requested URL

I am currently in the process of integrating an Angular 2 application with a Java Spring Boot backend. As of now, I have placed my Angular 2 files under src/main/resources/static (which means that both the Angular and Spring apps are running within the same app on the same port).

My goal is to perform an HTTP GET request like this:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Language } from '../model/language';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class LanguageService {

    constructor(private http: Http) { }

    private langUrl = 'api/languages'; 

    getLanguages() : Observable<Language[]> {
         return this.http.get(this.langUrl)
                         .map((res:Response) => res.json())
     }
}

In the code snippet above, error handling has been intentionally omitted from the GET method as it was causing misleading errors. The current error message being displayed is:

Error: Uncaught (in promise): Error: Error in :0:0 caused by: Response with status: 404 Not Found for URL: api/languages
Error: Error in :0:0 caused by: Response with status: 404 Not Found for URL: api/languages
    at ViewWrappedError.BaseError [as constructor] (http://localhost:8000/node_modules/@angular/core/bundles/core.umd.js:1179:31) [angular]
    at ViewWrappedError.WrappedError [as constructor] (http://localhost:8000/node_modules/@angular/core/bundles/core.umd.js:1232:20) [angular]
    at new ViewWrappedError (http://localhost:8000/node_modules/@angular/core/bundles/core.umd.js:6552:20) [angular]
//more output here - will provide full stack trace if needed

The URL

http://localhost:8080/api/languages
is being handled by a Java Spring controller and functions correctly when using Postman or a web browser.

Based on my observations, it seems that the 404 Error is not originating from the server because:

  • No activity related to the error is seen in the server logs.
  • The same result is obtained regardless of whether the server-side is up or down.

My assumption is that there might be a misconfiguration in my Angular 2 setup, however, I have not found any relevant tips in the documentation.

I have experimented with different URLs such as

http://localhost:8080/api/languages
, /api/languages, api/languages, another/working/server/endpoint - all resulting in the same error message.

I even attempted to utilize JSONP as outlined here, but encountered a separate issue where JSONP was not injected into the Language Service constructor (this specific problem may warrant a separate discussion).

A similar inquiry was discovered, yet remains unanswered thus far.

If anyone has suggestions on rectifying this issue or has faced a similar challenge before, any assistance or feedback would be greatly appreciated.

Thank you.

Answer №1

The cause of the error stemmed from my utilization of the Angular Tour of Heroes application as a framework for my project, without removing a certain dependency.

"angular-in-memory-web-api": "~0.2.4",

In addition to that, I also failed to exclude InMemoryWebApiModule from app.module.ts. Consequently, all requests were being intercepted by InMemoryWebApiModule (even though I did not directly invoke it as instructed in the Tour of Heroes Tutorial), which led to no XMLHttpRequests appearing in the 'Network' tab of the browser debugger.

Upon eliminating the mentioned dependency from both package.json and the node_modules directory, the functionality was promptly restored. However, I had to make adjustments to the service code in order to correctly parse Json into TypeScript objects, as shown below:

getLanguages(): Promise<Language[]> {
    return this.http.get(this.langUrl)
        .toPromise()
        .then(response => response.json() as Language[])
        .catch(this.handleError);
}

This might be considered a novice error, but I trust that this message will spare someone else a few hours of troubleshooting.

Answer №2

Dealing with a comparable problem, I spent a lot of time researching and finally managed to resolve the 404 error by following the guidance provided in this resource. The sequence of imports turned out to be crucial.
Hopefully, this solution proves beneficial to others facing a similar issue.

Answer №3

If you are using Chrome or Firefox, you have the ability to view all HTTP requests and responses made by your application (simply press F12 and go to the Network tab). Since you mentioned that it is functioning correctly in your browser or Postman, comparing both requests should help you identify any discrepancies quickly.

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

Having trouble accessing undefined properties? Facing issues with the latest Angular version?

Why am I encountering an error and what steps can be taken to resolve it? Currently using the latest version of Angular. ERROR TypeError: Cannot read properties of undefined (reading 'id') Here is the JSON data: { "settings": [ { ...

Investigating sibling HTML elements using an Angular directive

When working with Angular 10, my goal is to access a sibling element within my directive. This is illustrated by the following code snippet: <label myDirective for="foo" ... <input id="foo" formControlName="xyz" ... Wit ...

Determining the name of the currently focused DOM element in Angular2

How can I detect the name of a selected element from a group of select elements on a page? For example: <select (click)="functionDetectName()" name="test1"> <select (click)="functionDetectName()" name="test2"> <select (click)="functionDete ...

Incorporate the Angular router within markdown hyperlinks

When utilizing ngx-markdown to display my FAQ, I include links to both external resources (beginning with http) and internal content (starting with /). I am interested in passing the Angular router to my markedOptionsFactory so that I can easily navigate ...

Working with Arrays of Objects in Typescript with Angular

I am currently trying to define an array of objects in my Typescript code. However, I am encountering issues when accessing these objects. Below is the snippet of my code along with a screenshot showing the output of this.attachments. info: Info[]; if (t ...

What is the best way to transfer a variable between components in Angular without using the HTML page, directly within the components themselves?

Within the child component, I am working with a string: @Input() helloMessage:string; I am looking to assign a value to this string from another string in the parent component and utilize it within the child component without displaying the value in the h ...

Different methods for organizing an array of strings based on eslint/prettier

I possess an assortment of keys that I desire to sort in alphabetical order whenever I execute eslint --fix/prettier. My inference is that such a feature does not exist by default due to its potential impact on the code's behavior. Therefore, my quer ...

When an input event is dispatched in a unit test, the value changes of a form are not activated

Currently, I am testing a scenario where I need to verify if a value changes on the form when input is typed in. This particular project utilizes Nrwl nx as well as jest for testing purposes. The component code snippet is as follows: export class InputNu ...

Cross-Origin Resource Sharing (CORS) Issue: HTTP status is not okay. GoLang Mux API

When trying to perform HTTP requests using an Angular 17 App, I keep encountering the following response from the browser: Access to XMLHttpRequest at 'http://localhost:8082/login' from origin 'http://localhost:4200' has been blocked ...

Limiting the assignment of type solely based on its own type, without considering the components of the type

I have defined two distinct types: type FooId = string type BarId = string These types are used to indicate the specific type of string expected in various scenarios. Despite TypeScript's flexibility, it is still possible to perform these assignment ...

What is the best way to ensure that multiple queries are returned in the correct sequence?

In the interface below, there is a search input box along with data displayed. As you type in the search input, the data below filters accordingly. Each letter typed triggers a request to retrieve the relevant data. For instance, if you type "folder," the ...

Having difficulty in converting JSON objects into key/value pairs in Angular 7

I have a task to convert my JSON data from its current format as shown below: cacheMapDataDto = [{ "cacheName": "cache_nchl_individual_type", "count": 2, "mapObj": { "NCHL_BI_BATCH_VERIFICATION": false, "NCHL_STL_BATCH_VERIFICATIO ...

Constantly visible scrolling feature on material side navigation

Is there a way to keep the scroll bar in the sidenav always visible, even when the content is within the Y axis limits? This would prevent the scroll bar from fading in and out every time I open or close one of the mat-menu-items that function as accordio ...

Is it possible for the NativeScript CLI to generate spec files automatically?

As I delved into NativeScript today, I couldn't help but notice that the tabbed template app it generated didn't come with spec files like those generated by Angular CLI. Is there a way to incorporate Karma and Jasmine into the app creation proce ...

Sort information based on the initial letter

My challenge is to accurately filter data by the starting letter only, not including middle letters. For example, if I have the word "Karnataka" and want to filter by the letter "K", searching with middle letters like "rna" still filters the result. Howe ...

creating interactive tabs in angular using dynamic json values

Currently I am working on a material tab feature where I aim to dynamically generate tabs based on the values from my JSON data. Below is the JSON data: [ { "regionName": "EMEA", "regionCurrency": "USD", "organizationName": "XYZ", "orga ...

Trouble retrieving child structural directive within parent structural directive

Seeking to connect parent structural directive with child structural directive. This shows my attempt to access the child element @Directive({ selector: '[appChildStruralDirective]' }) export class ChildStruralDirective { constructor(privat ...

Style the date using moment

All languages had a question like this except for JavaScript. I am trying to determine, based on the variable "day," whether it represents today, tomorrow, or any other day. ...

Transforming an ordinary JavaScript object into a class instance

As I was delving into Angular's documentation on "Interacting with backend services using HTTP", I came across the following statement in the "Requesting a typed response" section: ...because the response is a plain object that cannot be automatical ...

Matching packages with mismatched @types in Webpack 2: A comprehensive guide

Having trouble implementing SoundJS (from the createJS framework) in my TypeScript project using webpack 2. In my vendors.ts file, I have the following import: import "soundjs"; Among other successful imports. The @types definitions installed via npm a ...