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

Is there a way to obtain asynchronous stack traces using Node.js and TypeScript?

When working with TypeScript, I encountered an issue with stack traces. It seems that only the bottommost function name is displayed. My setup includes Node.js v12.4.0 on Windows 10 (1803). Below is the code snippet: async function thrower() { throw new ...

Is it possible to use conditional logic on child elements in formkit?

I am a bit confused about how this process functions. Currently, I am utilizing schema to create an address auto complete configuration. My goal is to have the option to display or hide the fields for manual input. This is the current appearance of the ...

Restricting the types within a generic union type in TypeScript

//Custom declaration: interface TickListFilter { type: "tickList"; value: string; } interface ColorFilter { type: "color" value: ColorValueType } type FilterType = TickListFilter | ColorFilter; ... updateValue = (filte ...

The Vue route parameters are not recognized within the function type

Seeking assistance on extracting parameters from my route in a vue page, I have the following implementation: <script lang="ts"> import { defineComponent } from 'vue'; import { useRoute } from 'vue-router'; export ...

angular slickgrid grid date formatting only applies to grid view

this.columnDefinitions = [ { id: 'edit', field: 'id', excludeFromColumnPicker: true, excludeFromGridMenu: true, excludeFromHeaderMenu: true, formatter: Fo ...

After integrating React Query into my project, all my content vanishes mysteriously

Currently, I am utilizing TypeScript and React in my project with the goal of fetching data from an API. To achieve this, I decided to incorporate React Query into the mix. import "./App.css"; import Nav from "./components/Navbar"; impo ...

The requested 'export '_supportsShadowDom' could not be located within the module '@angular/cdk/platform'

Even though I have installed all the required libraries to run my Angular application, I am still encountering build errors. Error: "export '_supportsShadowDom' was not found in '@angular/cdk/platform'" I am unable to identify the root ...

Exporting from Excel is causing dates and times to be displayed as numbers instead

Having trouble with a specific date while exporting an Excel file. Refer to the screenshot of the Excel file for clarity: https://i.stack.imgur.com/7mFE4.png The date '01/02/2019 00:00:00' is being treated as a number instead of displaying corre ...

What is the solution for resolving the error message "Property '' does not exist on type 'typeof import'"?

Hi everyone, I'm a new Angular developer who is working on implementing authentication. I recently added the auth0-angular package to my project and now I'm encountering an error when creating a WebAuth() instance in my code editor (VS Code). Th ...

Tips on implementing zod schema types with remapped fields using the toZod method

I'm currently working on mapping a schema key to a different name in my database interface Country { isoCode: string, nameEn: string, nameDe: string, phone: string, bla: string } const CountryJson = { i ...

Restricting the type of user input in HTML forms

Requirements: Input must be a whole number between 2 and 99, inclusive. Current Solution: <input required type="number" min="2" max="99" oninput="this.value = Math.abs(this.value)" maxLength="2" matInp ...

When using Angular9 with PrimeNG fullcalendar, it may encounter issues such as errors stating "Cannot find namespace 'FullCalendarVDom'." and "Please import the top-level fullcalendar lib"

Using primeng p-fullcalendar in my angular application. Encountering an error in the command-line: 'Cannot find namespace 'FullCalendarVDom' Also seeing this error in the browser: 'Please import the top-level fullcalendar lib before a ...

How can models be aggregated in SQL by connecting them through other models?

I am working with a backend express API that utilizes sequelize. In my sequelize models, a Citizen is linked to a Street, which in turn is associated with a Town, and the Town is connected to a State. I can easily count the citizens on a specific Street by ...

Exploring the data types of dictionary elements in TypeScript

I have a model structured like this: class Model { from: number; values: { [id: string]: number }; originalValues: { [id: string]: number }; } After that, I initialize an array of models: I am trying to compare the values with the o ...

Generate a new data structure by pairing keys with corresponding values from an existing

Imagine having a type named Foo type Foo = { a: string; b: number; c: boolean; } Now, I am looking to create a type for an object containing a key and a value of a designated type T. The goal is for the value's type to be automatically determin ...

How to implement saving TypeScript Map() in Firebase Cloud Functions?

I am currently developing a Firebase Cloud Functions application using TypeScript that is designed to save an instance of Map() to Cloud Firestore. The map consists of user IDs as keys and objects with 2 simple attributes as values. Due to the dynamic natu ...

Issue connecting database with error when combining TypeORM with Next.js

I am attempting to use TypeORM with the next.js framework. Here is my connection setup: const create = () => { // @ts-ignore return createConnection({ ...config }); }; export const getDatabaseConnection = async () => { conso ...

Arrange two Angular 2 divs in a single row, with one positioned below the

Good Evening, I have a project in angular and I need help with styling. Specifically, I have 3 divs - card, table, and map. I want the card and table to be in the same row, and the map to be below them with double the size. The top left should have item in ...

I am facing conflicts between vue-tsc and volar due to version discrepancies. How can I resolve this problem?

My vsCode is alerting me about an issue: ❗ The Vue Language Features (Volar) plugin is using version 1.0.9, while the workspace has vue-tsc version 0.39.5. This discrepancy may result in different type checking behavior. vue-tsc: /home/tomas/Desktop/tes ...

Leveraging Shared and CoreModule in Ionic

In the recommended styleguide found at https://angular.io/guide/styleguide#core-feature-module, it is suggested to implement a SharedModule and CoreModule in an Angular application. I am curious if utilizing these modules would also be beneficial in an Io ...