I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

AngularTypescript

Angular Problem Overview


I'm using Angular 4 HttpClient to send requests to external service. It is a very standard setup:

this.httpClient.get(url).subscribe(response => {
  //do something with response
}, err => {
  console.log(err.message);
}, () => {
  console.log('completed');
}

The problem is, when the request fails I see a generic Http failure response for (unknown url): 0 Unknown Error message in console. Meanwhile, when I inspect the failed request in chrome I can see the response status is 422, and in the "preview" tab I see the actual message desribing failure cause.

How do I access the actual response message I can see in chrome dev tools?

Here's a screenshot demonstrating the problem: enter image description here

Angular Solutions


Solution 1 - Angular

The problem was related to CORS. I noticed that there was another error in Chrome console: > No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200'; is therefore not allowed access. The response had HTTP status code 422.`

This means the response from backend server was missing Access-Control-Allow-Origin header even though backend nginx was configured to add those headers to the responses with add_header directive.

However, this directive only adds headers when response code is 20X or 30X. On error responses the headers were missing. I needed to use always parameter to make sure header is added regardless of the response code:

add_header 'Access-Control-Allow-Origin' 'http://localhost:4200' always;

Once the backend was correctly configured I could access actual error message in Angular code.

Solution 2 - Angular

In case anyone else ends up as lost as I was... My issues were NOT due to CORS (I have full control of the server(s) and CORS was configured correctly!).

My issue was because I am using Android platform level 28 which disables cleartext network communications by default and I was trying to develop the app which points at my laptop's IP (which is running the API server). The API base URL is something like http://[LAPTOP_IP]:8081. Since it's not https, android webview completely blocks the network xfer between the phone/emulator and the server on my laptop. In order to fix this:

Add a network security config

New file in project: resources/android/xml/network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <!-- Set application-wide security config -->
  <base-config cleartextTrafficPermitted="true"/>
</network-security-config>

NOTE: This should be used carefully as it will allow all cleartext from your app (nothing forced to use https). You can restrict it further if you wish.

Reference the config in main config.xml

<platform name="android">
    ...
    <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
        <application android:networkSecurityConfig="@xml/network_security_config" />
    </edit-config>
    <resource-file src="resources/android/xml/network_security_config.xml" target="app/src/main/res/xml/network_security_config.xml" />
    ....
</platform>

That's it! From there I rebuilt the APK and the app was now able to communicate from both the emulator and phone.

More info on network sec: https://developer.android.com/training/articles/security-config.html#CleartextTrafficPermitted

Solution 3 - Angular

working for me after turn off ads block extension in chrome, this error sometime appear because something that block http in browser

enter image description here

Solution 4 - Angular

If you are using .NET Core application, this solution might help!

Moreover this might not be an Angular or other request error in your front end application

First, you have to add the Microsoft CORS Nuget package:

Install-Package Microsoft.AspNetCore.Cors

You then need to add the CORS services in your startup.cs. In your ConfigureServices method you should have something similar to the following:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
}

Next, add the CORS middleware to your app. In your startup.cs you should have a Configure method. You need to have it similar to this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
ILoggerFactory loggerFactory)
{
    app.UseCors( options => 
    options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
 	app.UseMvc();
}

The options lambda is a fluent API so you can add/remove any extra options you need. You can actually use the option “AllowAnyOrigin” to accept any domain, but I highly recommend you do not do this as it opens up cross origin calls from anyone. You can also limit cross origin calls to their HTTP Method (GET/PUT/POST etc), so you can only expose GET calls cross domain etc.

Solution 5 - Angular

For me it was caused by a server side JsonSerializerException.

> An unhandled exception has occurred while executing the request > Newtonsoft.Json.JsonSerializationException: Self referencing loop > detected with type ...

The client said:

POST http://localhost:61495/api/Action net::ERR_INCOMPLETE_CHUNKED_ENCODING
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false}

Making the response type simpler by eliminating the loops solved the problem.

Solution 6 - Angular

This error was occurring for me in Firefox but not Chrome while developing locally, and it turned out to be caused by Firefox not trusting my local API's ssl certificate (which is not valid, but I had added it to my local cert store, which let chrome trust it but not ff). Navigating to the API directly and adding an exception in Firefox fixed the issue.

Solution 7 - Angular

A similar error can occur, when you didn't give a valid client certificate and token that your server understands:

Error: > Http failure response for (unknown url): 0 Unknown Error

Example code:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

class MyCls1 {

  constructor(private http: HttpClient) {
  }

  public myFunc(): void {

    let http: HttpClient;

    http.get(
      'https://www.example.com/mypage',
      {
        headers:
          new HttpHeaders(
            {
              'Content-Type': 'application/json',
              'X-Requested-With': 'XMLHttpRequest',
              'MyClientCert': '',        // This is empty
              'MyToken': ''              // This is empty
            }
          )
      }
    ).pipe( map(res => res), catchError(err => throwError(err)) );
  }

}

Note that both MyClientCert & MyToken are empty strings, hence the error.
MyClientCert & MyToken can be any name that your server understands.

Solution 8 - Angular

I was getting that exact message whenever my requests took more than 2 minutes to finish. The browser would disconnect from the request, but the request on the backend continued until it was finished. The server (ASP.NET Web API in my case) wouldn't detect the disconnect.

After an entire day searching, I finally found this answer, explaining that if you use the proxy config, it has a default timeout of 120 seconds (or 2 minutes).

So, you can edit your proxy configuration and set it to whatever you need:

{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false,
    "timeout": 6000000
  }
}

Now, I was using agentkeepalive to make it work with NTLM authentication, and didn't know that the agent's timeout has nothing to do with the proxy's timeout, so both have to be set. It took me a while to realize that, so here's an example:

const Agent = require('agentkeepalive');

module.exports = {
    '/api/': {
        target: 'http://localhost:3000',
        secure: false,
        timeout: 6000000,          // <-- this is needed as well
        agent: new Agent({
            maxSockets: 100,
            keepAlive: true,
            maxFreeSockets: 10,
            keepAliveMsecs: 100000,
            timeout: 6000000,      // <-- this is for the agentkeepalive
            freeSocketTimeout: 90000
        }),
        onProxyRes: proxyRes => {
            let key = 'www-authenticate';
            proxyRes.headers[key] = proxyRes.headers[key] &&
                proxyRes.headers[key].split(',');
        }
    }
};

Solution 9 - Angular

I'm using ASP.NET SPA Extensions which creates me a proxy on ports 5000 and 5001 that pass through to Angular's port 4200 during development.

I had had CORS correctly setup for https port 5001 and everything was fine, but I inadvertently went to an old bookmark which was for port 5000. Then suddenly this message arose. As others have said in the console there was a 'preflight' error message.

So regardless of your environment, if you're using CORS make sure you have all ports specified - as the host and port both matter.

Solution 10 - Angular

If this is a node service, try the steps outlined here

Basically, it's a Cross-Origin Resource Sharing (CORS) error. More information about such errors here.

Once I updated my node service with the following lines it worked:

let express = require("express");
let app = express();

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");    
    next();
  });

Solution 11 - Angular

For me it was a browser issue, since my requests were working fine in Postman.

Turns out that for some reason, Firefox and Chrome blocked requests going to port 6000, once I changed the ASP.NET API port to 4000, the error changed to a known CORS error which I could fix.

Chrome at least showed me ERR_UNSAFE_PORT which gave me a clue about what could be wrong.

Solution 12 - Angular

If you are using Laravel as your Backend, then edit your .htaccess file by just pasting this code, to solve problem CROS in your Angular or IONIC project

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

Solution 13 - Angular

If you have a proper cors header in place. Your corporate network may be stripping off the cors header. If the website is externally accessible, try accessing it from outside your network to verify whether the network is causing the problem--a good idea regardless of the cause.

Solution 14 - Angular

if you are using nodejs as backend, here are steps to follow

  1. install cors in your backend app

    npm install cors

  2. Add this code

     const cors = require('cors');
     const express = require('express');
     const expressApp = express();
     expressApp.use(cors({
         origin: ['http://localhost:4200'],
         "methods": "GET,PUT,POST",
         "preflightContinue": false,
         "optionsSuccessStatus": 204,
         credentials: true
     }));
    

Solution 15 - Angular

Is not as old as other questions, but I just struggled with this in an Ionic-Laravel app, and nothing works from here (and other posts), so I installed https://github.com/barryvdh/laravel-cors complement in Laravel and started and it works pretty well.

Solution 16 - Angular

Mine was caused by an invalid relationship in the models I was trying to query. Figured out by debugging the response it crashed at the relation.

Solution 17 - Angular

For me it wasn't an angular problem. Was a field of type DateTime in the DB that has a value of (0000-00-00) and my model cannot bind that property correct so I changed to a valid value like (2019-08-12).

I'm using .net core, OData v4 and MySql (EF pomelo connector)

Solution 18 - Angular

> Add This Codes in your connection file

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT,GET,POST,DELETE");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Solution 19 - Angular

In asp.net core, If your api controller doesn't have annotation called [AllowAnonymous], add it to above your controller name like

[ApiController]
    [Route("api/")]
    [AllowAnonymous]
    public class TestController : ControllerBase

Solution 20 - Angular

You must use --port when serve server ng serve --open --port 4200

    export class DatabaseService {
  baseUrl: String = "http://localhost:8080/";
  constructor(private http: HttpClient) { }


  saveTutorial(response) {
    var fullUrl = this.baseUrl + "api/tutorials";
   
    return this.http.post(fullUrl,response);
  }
}

Solution 21 - Angular

I had the same issue. I used grdl's answer above and added a cors configuration to my server like the one below and the problem was solved.

{
"cors": [
    {
      "origin": [“*”],
      "method": ["GET"],
      "responseHeader": ["Content-Type"],
      "maxAgeSeconds": 3600
    }
  ]
}

Look at the specific cors config help for your server to see how to set it up.

Solution 22 - Angular

My error was that the file was too large (dotnet core seems to have a limit @~25Mb). Setting

  • maxAllowedContentLength to 4294967295 (max value of uint) in web.config
  • decorating the controller action with [DisableRequestSizeLimit]
  • services.Configure(options => { options.MultipartBodyLengthLimit = 4294967295; }); in Startup.cs

solved the problem for me.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongrdlView Question on Stackoverflow
Solution 1 - AngulargrdlView Answer on Stackoverflow
Solution 2 - AngularhaggyView Answer on Stackoverflow
Solution 3 - AngularDwi Yanuar IlhamView Answer on Stackoverflow
Solution 4 - AngularsathishView Answer on Stackoverflow
Solution 5 - AngularPerrierView Answer on Stackoverflow
Solution 6 - AngularfraxView Answer on Stackoverflow
Solution 7 - AngularManohar Reddy PoreddyView Answer on Stackoverflow
Solution 8 - AngularMarcos DimitrioView Answer on Stackoverflow
Solution 9 - AngularSimon_WeaverView Answer on Stackoverflow
Solution 10 - AngularFistOfFuryView Answer on Stackoverflow
Solution 11 - AngularShahin DohanView Answer on Stackoverflow
Solution 12 - Angularshirjeel khanView Answer on Stackoverflow
Solution 13 - AngularN-ateView Answer on Stackoverflow
Solution 14 - AngularYouBeeView Answer on Stackoverflow
Solution 15 - AngularGerson MontenegroView Answer on Stackoverflow
Solution 16 - AngularJ.Kirk.View Answer on Stackoverflow
Solution 17 - AngularLuis LopezView Answer on Stackoverflow
Solution 18 - AngularAbdelhakim EzzahraouiView Answer on Stackoverflow
Solution 19 - AngulardgncnView Answer on Stackoverflow
Solution 20 - AngularWai Yan MoungView Answer on Stackoverflow
Solution 21 - AngularKrithikaView Answer on Stackoverflow
Solution 22 - AngularSpikolynnView Answer on Stackoverflow