Angular 8 shows an error message stating "Unknown Error" when making a REST API request

My goal is to retrieve data from the server using a REST API service. The code snippet below is from my service.ts file:

getCategories(): Observable<Category> {

    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin' : '*',
        'Access-Control-Allow-Methods' : 'POST'
      })
    };
    
    return this.http.post<Category>(this.apiURL+'api', JSON.stringify({"type":"get_categories"}), httpOptions )
        .pipe(
          retry(0),
        )
}

However, when I run this code, I encounter the following error message:

Object { headers: {…}, status: 0, statusText: "Unknown Error", url: "http://localhost/test/api", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost/test/api: 0 Unknown Error", error: error }

I have searched through numerous resources but have not found a solution yet.

Answer №1

This particular issue arises due to the following error:

ERROR ReferenceError: "httpOptions is not defined"

The reason for this error is that you are attempting to use httpOptions outside the scope of the getCategories function.

To resolve this, it is recommended to modify your code as shown below:

getCategories(): Observable<Category> {
   const httpOptions = {
        headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin' : '*',
        'Access-Control-Allow-Methods' : 'GET, POST, PUT, DELETE'
        })
    };

   return this.http.post<Category>(this.apiURL+'api', JSON.stringify({"type":"get_categories"}), httpOptions )
    .pipe(
      retry(0),
      //catchError(this.handleError)
    )
  }

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 invoking both a typescript arrow function and a regular javascript function within one event

Is it possible to call both a JavaScript function and a TypeScript function from the same onClick event in a chart? I am new to TypeScript and Angular, so I'm not sure if this is achievable. The issue at hand is that I need to invoke a JavaScript fun ...

Showing json information in input area using Angular 10

I'm facing an issue with editing a form after pulling data from an API. The values I retrieve are all null, leading to undefined errors. What could be the problem here? Here's what I've tried so far: async ngOnInit(): Promise<void> ...

What is the best way to permit multiple instances of a component in separate tabs without losing their individual states?

My application is equipped with a lazy loading tab system that is controlled by a service. When a user chooses an option from the navigation menu, two key actions take place : An entry is appended to the tabs array within the tab service. A new route is t ...

Unique Angular custom validator for template-driven forms

Apologies for any language barriers, I am currently working on an Angular 6 application and I am in the process of adding a custom validator. This validator checks if a file exists in the database. However, I would like this validator to be triggered only ...

Combine the remaining bars by stacking the highest one on top in Highchart

Making use of stacking to display the highest value as the longest column/bar, with smaller values being merged within the highest one, can create a more visually appealing stack chart. For example, when looking at Arsenal with values of 14 and 3, ideally ...

Upon completion of the function, the ForEach loop commences

I'm encountering an issue with my code. I am trying to verify if there is an item in the cutlist array that has a material_id which does not exist in the materials database. However, the code within the forEach loop is being executed after the functio ...

You cannot assign the type 'void' to the type 'ObservableInput<Action>'

I'm encountering a type error when I attempt to dispatch an observable of actions within my effect. The error message I'm receiving is as follows: @Effect() rideSummary$: Observable<Action> = this.actions$.pipe( ofType<GetRi ...

In React TS, the function Window.webkitRequestAnimationFrame is not supported

I'm facing an issue where React TS is throwing an error for window.webkitRequestAnimationFrame and window.mozRequestAnimationFrame, assuming that I meant 'requestAnimationFrame'. Any suggestions on what to replace it with? App.tsx import Re ...

Can you explain the meaning of `images:Array<Object> = [];` in TypeScript?

Recently, I stumbled upon this code snippet in TypeScript images:Array<Object> = []; I'm curious, what exactly does the "<>" notation signify? ...

Store the HttpRequest value within the component

I am encountering an issue with the Http Request value. I am sending an Http request to an Express API rest, and I want to display the value throughout my component. The data is available in the observable but not in other functions of my component. Can ...

What is the procedure for linking my SQL database with Angular?

This is a sample HTML code snippet to create a sign-in form: <div class="col-md-8"> <form (submit)="onSubmit()" method="POST"> <input type="text" class="form-control mb-2" name="names" [(ngModel)]="profileForm.name" placeholder="Usern ...

Steps for initiating an Angular 4 project

While most developers have moved on to Angular 5, I was tasked with creating a project using Angular 4. After conducting research for several days, I discovered that downgrading the Angular CLI would allow me to accomplish this. By following this approach, ...

Is there a possibility of Typescript expressions `A` existing where the concept of truthiness is not the same as when applying `!!A`?

When working with JavaScript, it is important to note that almost all expressions have a "truthiness" value. This means that if you use an expression in a statement that expects a boolean, it will be evaluated as a boolean equivalent. For example: let a = ...

Experience Next.js 13 with Chakra UI where you can enjoy Dark Mode without the annoying White Screen Flash or FOUC (flash of unstyled content)

Upon refreshing the page in my Next.js 13 /app folder application using Chakra UI, I notice a few things: A momentary white flash appears before switching to the dark theme. The internationalization and font settings momentarily revert to default before l ...

Does one require the express.js framework in order to create a web application using nodeJS?

Exploring the creation of a basic web application using HTML, NodeJS, and Postgres. Can this be achieved without incorporating the ExpressJS framework? Seeking guidance on performing CRUD operations with NodeJs, Javascript, and Postgres sans ExpressJS. G ...

Track and log async routes for undefined values once await is complete

Currently facing challenges with multiple queries and synchronous code while writing an Express endpoint in TypeScript to update a user's password in the database. The issue I am encountering is that when attempting to await the return of a function, ...

Enhancing menu item visibility with Typescript and Vue.js 3: A step-by-step guide

How can I dynamically highlight the active menu item in my menu? I believe that adding v-if(selected) and a function might be the way to go in the first template. <template> <MenuTreeView @selected='collapsedMenuSelected' :items=&apo ...

How can one identify the optional fields in TypeScript interfaces generated from GRPC proto-files?

Within my ts-node project, I am converting TypeScript from gRPC proto files, where certain properties are denoted as optional. However, the resulting TS interfaces end up with ALL properties being marked as optional. Additionally, an extra "_" prefixed pr ...

Navigating on button click in Angular 5

Is there a way to navigate to a home component when the user clicks a button without using routerLink? I know how to do it with <a href=””>, but not with routerLink. Can this be achieved by utilizing a button click event? <a class="nav-item n ...

Different ways to modify the style of a MenuItem component in PrimeNG

Seeking advice on customizing the look of a MenuItem in PrimeNG. Here's what I have attempted so far: <p-menu [style]="{'width': '400px'}" #menuOpcoesLista popup="popup" [model]="opcoesListaCS" appendTo="body"></p-menu> ...