What is the process for interpreting the status code retrieved from an HTTP Post request?

When sending a POST request to a backend and attempting to read the status code, I encountered the following result: status-code:0

Below are my functions:

Service:

signIn(uname:string, pass:string): Observable<any> {
    let headers = new Headers({
        'Content-Type': 'application/json',
        'Uname':uname,
        'Password':pass
    });
    let opt = new RequestOptions({ headers: headers, withCredentials: true  });
    let data = {};
    return this.http.post( url, data, opt )
    .map(res => {
        return res.json();
    })
    .catch( this.handleError );
}

private handleError(error:Response | any){
    let details = error.json();
    console.log('STATUS CODE: ' + error.status);
    return Observable.throw(details || error);
}

Component:

login(uname: string, pass: string) {
    this.user.signIn(uname, pass).subscribe(
        res => {},
        err => {
            console.log('ERR: ' + JSON.stringify(err)); 
            // returns {"isTrusted":true}
        }
    );
}

I aim to extract the status code like 404, 401, or 403. In my case, I can observe the status 404 in Chrome console, hence I would like to exhibit an errorMsg corresponding to the status code error.

Upon switching to the Network tab in the console, under the Response section, I find:

{"code":404,"reason":"Not Found","message":"Resource 'user/auth' not found"}

Further outputting error within the handleError() function fetches:

handleErrorObservable: {"_body":{"isTrusted":true},"status":0,"ok":false,"statusText":"","headers":{},"type":3,"url":null}

Is there an approach to resolve this issue based on the provided code, or where could the mistake be occurring?

Answer №1

Thanks to resolving the issue related to CORS, I successfully retrieved the status code from the Response.

I discovered a helpful article on Restricting access to a server using CORS.

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

The issue of NestJS dependency injection not working within the MongooseModule.forFeatureAsync function call has been encountered

I'm having an issue setting up a pre-save hook on my User model. Here's the code snippet from my users.module.ts: @Module({ controllers: [ UsersController, ], exports: [ UsersService, ], providers: [ UsersService, ], imp ...

Bizarre npm setup

I'm new to Node and struggling with upgrading my package to enable web workers. I'm attempting to move from Angular 6.x.x to 7.x.x and then to 8.x.x. However, every time I try to install updates, it initially seems like it's successful but e ...

Troubleshooting Typescript compilation issues following an upgrade to a React Native project

I am facing a challenge while updating a react native project from version 0.63.3 to 0.67.0. When attempting to run npm run tsc, I encounter numerous errors indicating that the typescript packages are not compatible with their original packages. Here is a ...

Issue encountered after updating to Spartacus 3.0 from 2.0: Unable to access the 'findStores' property due to a TypeError

After upgrading to Spartacus 3.0 from 2.0, everything seems to be working fine except for this particular error that keeps popping up. I followed the steps provided by SAP team on the documentation site to add the storefinder module. Error in spartacus-co ...

Exporting a class from an index.ts file may result in a problem where the injected constructor is

Utilizing an index.ts file to manage exports, following the guidelines outlined in the Angular 2 style guide (https://github.com/mgechev/angular2-style-guide/blob/master/old/README.md#directory-structure), has been successful throughout my application deve ...

Creating a variable as a list of string arrays in TypeScript

Currently working with Angular 2.0, I am trying to declare a variable in a Typescript file that is a list of string arrays. I attempted using yAxis_val: list, but it is not functioning correctly. If anyone knows the proper way to achieve this, please prov ...

Ways to display the chosen value based on the item's index using Javascript in Angular

If you want to view the complete code, just click on this link. I have identified the main issue here. Check out the code here: https://stackblitz.com/edit/test-trainin-2?file=src/app/app.component.html The problem is when you interact with the green bal ...

I encountered an issue in my Angular application where I continually receive the error message stating "Module 'fs' cannot be found."

Within my service file, I have imported four crucial libraries: import * as async from "async"; import * as officegen from "officegen"; import * as path from "path"; import * as fs from "fs"; All seems to be functioning well with async, officegen, and pa ...

Tips for validating numeric fields that rely on each other with Yup

I am facing a challenge in setting up a complex validation using the library yup for a model with interdependent numeric fields. To illustrate, consider an object structured like this: { a: number, b: number } The validation I aim to achieve is ...

Is there a way to achieve region collapsing and expanding using #region / #endregion in TypeScript within Visual Studio Community Edition 2019?

For a while now, we've been utilizing "region collapsing" in TypeScript as shown below: //#region GUI handlers ...code related to handling GUI events... //#endregion This method has functioned well in VS2015 CE and VS2017 CE, with a small "-" or "+" ...

The electron application along with node.js and ng framework is having issues with the file path. It seems that the g.ps1 file cannot be loaded due to

Currently, I am attempting to compile a project using Windows 10 in Visual Studio Code, and my settings are as follows: 1) npm version 6.12 2) Node.js version 12.13 3) Angular CLI: 8.3.19 The issue arises when I try to execute ng serve, resulting in th ...

Angular2: Issue with service injection within service

Below is the code snippet I have written. Assuming you can grasp the purpose without further elaboration. @Injectable() export class Dispatcher { } @Injectable() export class TodoStore { constructor(@Inject(Dispatcher) private dispatcher:Dispatcher ...

Discovering identical objects in two arrays in Angular using TypeScript is a breeze

I've hit a roadblock with a TypeScript problem in my Angular service. I have an array of ingredients: private ingredients: Ingredient[] = [ new Ingredient('farina', 500), new Ingredient('burro', 80), new Ingredient('ucc ...

The issue arises due to conflicting indent configurations between eslint and @typescript-eslint/indent

Currently, I am using eslint and prettier in a TS express application. I am trying to set the tab width to 4, but it appears that there is a conflict between the base eslint configuration and the typescript eslint. When looking at the same line, this is w ...

Using Regex to replace special characters in TypeScript

I need assistance in removing the characters "?" and "/" from my inner HTML string. Can you guide me on how to achieve this using regex? For example, I would like to replace "?" with a space in the following content. "Hello?How are you?<a href="http:/ ...

Creating an array of custom objects in JavaScript.Initializing custom objects in an

Is there a proper way to prevent the error "Cannot read property 'length' of undefined" when initializing an array of custom objects in javascript? situation export class MyClass implements OnInit { myArray: MyObject[]; } example <div ...

Troubleshooting: Issues with accessing Angular/Typescript Class Getter property

I have a class defined as follows: export class Story { id: number; title: string; storyText: string; utcDate: string; get displayDate(): string { const today = new Date(); const postDate = new Date(this.utcDate); ...

Transform a nested AngularJS service into an Angular Observable service

Currently, I am working on migrating AngularJS(pre 1.5) services that use nested calls to a project being rebuilt in Angular(11). The challenge I'm facing is how to rewrite these services using RXJS. I have been searching for resources or detailed ex ...

Enhance your Angular experience by adding two new columns to your JSONArray table

I am faced with a JSON-Array dilemma. Array(8) 0: (3) ["Test", "1", "222"] 1: (3) ["Test", "2", "333"] 2: (3) ["Test", "3", "444"] 3: (3) ["Test", "4", "555"] 4: (3) ["Test", "5", "666"] 5: (3) ["Test", "6", "777"] 6: (3) ["Test", "7", "888"] I want to t ...

Using Typescript to override an abstract method that has a void return type

abstract class Base{ abstract sayHello(): void; } class Child extends Base{ sayHello() { return 123; } } The Abstract method in this code snippet has a return type of void, but the implementation in the Child class returns a number. S ...