Whenever I make a POST request to the API in Ionic 2, I encounter a "Connection refused (x192)" error

I have been struggling with an error in my code for the past two days and I can't seem to find a solution. Can someone please help me with this?

  1. The error message is as follows:

    [Error] WebSocket network error: The operation couldn’t be completed. Connection refused (x192)
    [Error] ERROR – Response {_body: XMLHttpRequestProgressEvent, status: 0, ok: false, …}
    Response {_body: XMLHttpRequestProgressEvent, status: 0, ok: false, statusText: “”, headers: Headers, …}Response
    
  2. Here is a snippet of the code that is causing the issue:

    import { Http, Headers, RequestOptions } from ‘@angular/http’;
    import { Injectable } from ‘@angular/core’;
    import ‘rxjs/add/operator/map’;
    
    /*
    Generated class for the RestapiServiceProvider provider.
    
    See https://angular.io/guide/dependency-injection for more info on providers
      and Angular DI.
    */
    
    @Injectable()
    export class RestapiServiceProvider {
    
        apiUrl = ‘http://localhost:8100/development/abc/public/api/v1/apiName’;
    
        constructor(public http: Http) {
            console.log(‘Hello RestapiServiceProvider Provider’);
        }
    
        getUsers() {
        
        // Code block goes here
        
        }
    }
    

Answer №1

Here's a suggestion you could try to see if it helps:

Rather than using:

apiUrl = ‘http://localhost:8100/development/abc/public/api/v1/apiName’;

Make sure there is a port associated with it, like 8100 for Ionic. Check if your API is running on a different port and make the necessary adjustments:

apiUrl = ‘http://localhost:<some_other_port_number>/development/abc/public/api/v1/apiName’;

Another Approach:

I'm not sure how you're handling post data on your server side, but consider this:

Your current code:

               `let data1 = JSON.stringify({
                    user_id: 14,
                    token: “dsfdsffsfsffsdfffsdffsfs”
                });`

Instead, change it to:

               `let data1 = {
                    user_id: 14,
                    token: “dsfdsffsfsffsdfffsdffsfs”
                }`

The issue may be that you are sending just a string without any label or key:

this.http.post(this.apiUrl, data1, options)

So, data1 should be sent as a JSON Object, not a string

You can try this with or without using proxies, depending on how your client side operates.

If the problem persists, refer to these resources:

Resolving Connection Refused Error

Hope this information proves helpful!

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

Height transition animation in Angular 2 - maintaining state consistency

I am currently working with an animation code that is linked to my component. animations:[ trigger('slide', [ state('show', style({ height: '*' })), state('hide ...

Patience is key when waiting for both subscriptions to be completed before proceeding with an

I am facing a challenge with two subscriptions as shown below: this.birthdays = await this.birthdaySP.getBirthdays(); this.birthdays.subscribe(groups => { const allBirthdayT = []; groups.map(c => { allBirthdayT.push({ key: c.pa ...

The NGX-Graph nodes mysteriously change color to deep black when the third property is applied

My goal is to create a tree structure using ngx-graph and have each node linked to a pop-up using "@material-extended/mde". However, I encountered an issue when trying to define the pop-up content based on each individual node by using the property "data". ...

Steer clear of duplicating template literal type entries when dealing with optional routes

My code includes a type called ExtractParams that extracts parameters from a URL string: type ExtractParams<Path extends string> = Path extends `${infer Start}(${infer Rest})` ? ExtractParams<Start> & Partial<ExtractParams<Rest>& ...

Can NgZone be utilized within a shared service instance?

I am currently working on creating an injectable singleton service for my application that will provide all components with information about the window width and height, as well as notify them when the page is scrolled or resized. Below is the code snipp ...

Choose the initial mat-option with mat-select functionality

In my app, I have several Angular Material select dropdowns with mat-options that are updated reactively based on other values (filtering of options). Here's an example: <mat-select #selects (selectionChange)='formChanges()' [placeholder ...

Tips for enhancing a table with extra functionality in Angular 6

Hi there! I've created a table using Angular 6 and now I'm looking to enhance it with some extra functionality: Implement an overall table search feature Allow users to sort the table by columns Add a "Page x of n" option for pagination I woul ...

What is the method for comparing fields within an input type in type graphql with the assistance of class validator decorators?

I am working with the following example input type: @InputType() class ExampleInputType { @Field(() => Number) @IsInt() fromAge: number @Field(() => Number) @IsInt() toAge: number } Can I validate and compare the toAge and fromAge fields in th ...

What is the appropriate Typescript return type to use for a $http request that only returns a successful response with no content?

I recently developed a Typescript service: class SettingsService implements ISettingsService { public info = {}; public backupInfo = {}; public userConfig = {}; public isLoaded = false; constructor( private $http: ng.IHttpSer ...

` `angular2 get the element reference of a component that is not a direct descendant` `

Within my application, the structure is as follows: <fin-header></fin-header> <main></main> <fin-footer></fin-footer> I would like to implement scrolling within the header to a specific component within main. However, ...

Deactivating Chrome Autofill once more in version 70.0.3538.67

Unfortunately, with the latest Chrome version 70.0.3538.67, all my previous methods of disabling autofill/autosuggest no longer seem to be effective. I am looking for a clean solution that is practical and efficient. Additionally, I have forms with a com ...

Mixing pipe operators with Angular Observables in an array

In my project, I have an interesting scenario where I am using Observables and piping them to multiple functions as shown below. getOrders(filters: any, page: any = 1, orderBy: string = 'deliver_on', sort: string = 'asc') { const op ...

Troubleshooting: Why is the Array in Object not populated with values when passed during Angular App instantiation?

While working on my Angular application, I encountered an issue with deserializing data from an Observable into a custom object array. Despite successfully mapping most fields, one particular field named "listOffices" always appears as an empty array ([]). ...

Creating a new JavaScript object using a Constructor function in Typescript/Angular

Struggling with instantiating an object from an external javascript library in Angular/Typescript development. The constructor function in the javascript library is... var amf = { some declarations etc } amf.Client = function(destination, endpoint, time ...

Is there a way to dynamically retrieve a JSON element in Typescript?

I am using a data grid throughout my application, and currently, I am retrieving the selected rowid with the following code. Here is the HTML snippet: <tbody> <tr *ngFor="let ddata of tableData.data; let i = index" (click)="setClickedRow(ddat ...

Compatibility of Typescript with local storage

Can Typescript interact with local storage in any way? I have been setting items using the following code: localStorage.setItem('someString', JSON.stringify(MyTypescriptObject)); This method stores the object as a plain string. For example: ...

Ways to assign unpredictable values (such as ids, dates, or random numbers) to a Domain Entity or Aggregate Root when it has been injected as dependencies

I am currently developing a frontend repository that follows an innovative hexagonal architecture approach with domain-driven design principles, and it utilizes Redux Toolkit. The development process involves Test-Driven Development (TDD) where I employ c ...

Local environments in Angular do not support file replacement

Within my angular.json file, I have set up configurations for both development and production environments. My goal is to prevent file replacement from occurring when running locally with 'ng serve', but allow it during Docker builds. Is there a ...

The issue with Angular 2's router.navigate not functioning as expected within a nested JavaScript function

Consider the app module: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { RouterModule } from '@angul ...

The interface 'children: string' does not share any properties with the type 'IntrinsicAttributes'.ts(2559)

When I export the component, the value from the input email does not appear as a VALUE property. How can I collect the text written in this exported component in my code? NOTE: I am working on developing a design system using STORYBOOK. export const Login ...