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

27

178

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

Summon answered 8/11, 2017 at 13:10 Comment(7)
try to log entire err object - not only the messageJudaica
I'm facing the same problem and was going to create a question for this too, here's the complete err object: gist.github.com/GO3LIN/7cffc3b0aa1f24d3e23e28cc907237fcEndor
Or better {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":null,"ok":false,"name":"HttpErrorResponse","message":"Http failure response for (unknown url): 0 Unknown Error","error":{"isTrusted":true}}Endor
@PavelAgarkov, It's not about logging only message. The HttpErrorResponse I recveive just doesn't contain the actual error message. Here's a screenshot of the problem. You can see there that the error I log has message saying "... unknown error..." but when you look at the request response preview above you can see the actual, meaningful message.Summon
Are you using a service worker?Bosworth
what is the url valueJosuejosy
for a quick mock api this one is very helpful (no CORS issues) - my-json-server.typicode.comKain
S
138

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.

Summon answered 14/11, 2017 at 21:6 Comment(9)
also the following link can be helpful for enabling CORS: learn.microsoft.com/en-us/aspnet/web-api/overview/security/…Appurtenance
where should this line be added?Evy
how do you add 'always' to an express.js .use function? Typically the structure is: app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "localhost:4200"); … }); As you can see the res.header allows for two parameters... a control string and a value. I have tried to add 'always' in various ways but they all seem to fail. Any suggestions?Granlund
@grdl, where the line add_header should be added?Virology
where add this line? I use php for my apiCeroplastics
The add_header line needs to be added to the configuration of Nginx server which serves the backend. Please mind that this is Nginx specific config. If you're using a different server you need to find its own way to ensure the Access-Control-Allow-Origin header is added.Summon
if you are using express, you have to add it as middleware to the express server. more info here enable-cors.org/server_expressjs.htmlShaynashayne
what if I use php, where can I add this lineChristcrossrow
Further to the answer above, add the following CORS configuration file to your server, and the issue will be resolved.Modulate
T
42

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

Ticktacktoe answered 17/5, 2019 at 0:43 Comment(5)
Thank a ton! I was also using an "http" url. Changed it to "https" and it worked. Btw, just changing a url to https won't work, you need a certificate to handle that. The server I was using supports both, so it was easier for me. Anyways, Thanks a Ton!Footboy
yes...for me it is about cleartext too....because i'm using http.. it would no be problem if i use https....but in case i still want to use http, i directly add android:usesCleartextTraffic="true" in application tag in AndroidManifest.xml ...and it's working....thanks for mention about cleartext...Implication
How can I enable this in Spring boot? I am sorry if the question is too trivial but I am a beginner and I can't find any solutions onlineRickrack
Thats brilliant mate, this just solved mine problem as well, thank you. :)Bracken
Thank you very much !Novelty
D
20

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.

Dilan answered 22/3, 2019 at 6:40 Comment(0)
K
18

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

Kiwanis answered 29/8, 2018 at 15:38 Comment(1)
for me it was uBlock Origin which blocked downloading file with 'analytics' in it's nameHeterophyte
M
7

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.

Merrow answered 21/2, 2018 at 9:56 Comment(0)
S
5

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.

Splatter answered 26/4, 2018 at 13:4 Comment(2)
I have gone through several CORS answers and one after another each one did not provide a solution when using Firefox. I looked at this post and thought, "no way this is it but I'm out of ideas what the hell" and sure enough it worked. Thank you so much!Cia
@frax, I had exactly the same case! Thanks! :)Nipping
C
5

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();
  });
Clydeclydebank answered 20/2, 2020 at 14:32 Comment(1)
only required to allow origin in local dev environment in my caseNoma
S
4

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.

Skepful answered 5/12, 2018 at 12:54 Comment(4)
i use this code in my ionic app . my ionic app used as index in my site. but this tricks cant help me . seems my apis in laravel need configuration maybe in ngnix or laravel or my docker host... i used cors middleware for cors enabled and it worked on my local with http but when deployed on docker cant call my api with httpsAddendum
when i call my rest apis from http those worked but when call https they didnt respond to my clients. and return Mixed Type error. i think there are certificate error or something like nginx configuration or .htaccess because i add cors middleware for cors and all things worked good without https. my client hosted on http call http result is ok . but when my client host on https and call https errors happenedAddendum
Ok, one solution is, go to the https:// url that you have, and click on the lock icon beside the https, download the certificate to a file, read that file via import/require/fs, then give/pass that certificate string to the call to the url, then it will work.Skepful
is there any way to catch "err" in app to handle this error?Politicking
O
4

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(',');
        }
    }
};
Ostrander answered 9/9, 2019 at 21:33 Comment(0)
T
2

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.

Tax answered 6/12, 2018 at 22:5 Comment(0)
E
2

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.

Ephemera answered 1/3, 2020 at 19:23 Comment(0)
I
1

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"
Irina answered 2/2, 2018 at 13:31 Comment(3)
You should never ever allow "*"! In general you know who is talking to your backend and you should set their host explicitly.Brain
@Brain but if you are doing an app for android the host it's not known. Will be every mobile that consume your service, am I right?Antifederalist
we needed to use cordova-plugin-advanced-http and the @ionic/native wrapper to have http calls from the device natively instead of using a browser-based ajax call. @AntifederalistAnnia
A
1

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.

Askja answered 6/11, 2018 at 19:50 Comment(0)
N
1

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");
Nepotism answered 2/1, 2020 at 17:49 Comment(0)
C
1

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
Craps answered 15/4, 2020 at 11:55 Comment(1)
This will disable the authentication for the whole controller.Infantile
B
1

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
     }));
    
Bufflehead answered 14/2, 2021 at 17:59 Comment(0)
M
1

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.

Modulate answered 28/4, 2022 at 7:40 Comment(0)
M
1

Let do some simple ones:

a) Network is disconnected - zero byte response.

b) I get this when I cancel a http call (yes you can do that)

c) During start up when I move pages too quickly it will cancel http calls because angular has not hooked up properly. I locked page to stop this one occurring.

d) We had a proxy in the middle and it terminated the connection after 30 seconds rather sending a HTTP timeout packet. If you look at the .net logs on back end you will see a client disconnected message. (these are not unusual as a user may just close their browser)

All of these have happened to me and I have no idea how to separate out which cause it is for any specific failure.

Micron answered 19/8, 2022 at 2:13 Comment(0)
M
1

In my case UseCors was placed after UseAuthentication / Authorization: No 'Access-Control-Allow-Origin' header is present on the requested resource when 401 response is returned from the server

Multiplex answered 7/12, 2022 at 7:34 Comment(0)
L
0

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.

Larry answered 17/8, 2018 at 11:6 Comment(0)
H
0

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.

Hangdog answered 1/9, 2018 at 14:3 Comment(0)
I
0

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)

Iapetus answered 14/11, 2019 at 11:16 Comment(0)
D
0

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);
  }
}
Docker answered 12/11, 2020 at 4:55 Comment(0)
D
0

2022-07-13

This is the easiest way but DON'T with PROD.

Inside index.html, add or edit the existing <meta http-equiv="Content-Security-Policy" content=". For example CORS blocked my access to local IIS Express https://localhost:44387/api/test, solution is have this

<meta http-equiv="Content-Security-Policy" content="
...
connect-src 'self' https://localhost:44387 https://anysite.com ...">
Dramatist answered 13/7, 2022 at 18:25 Comment(0)
I
0

I stumbled on the same error when connecting my Angular front end with Django REST API backend. The problem was simply not having installed cors headers. This can be fixed by

  1. Installing django-cors-headers. Do this by using pip

    pip install django-cors-headers

  2. Adding cors-headers to installed apps in /settings.py

INSTALLED_APPS = [ 'rest_framework', 'corsheaders' ]

  1. At the whatever line in your code, add this:

    CORS_ALLOW_ALL_ORIGINS =True

This fixed my issue. Hope it will be helpful to you.

Happy coding dev

Iliad answered 27/8, 2023 at 21:35 Comment(0)
L
0

As said by others contributors, most of the time this error happens when for some reason the browser block the outgoing request. The most common reason is CORS. But in my case the reason was Chrome (and every other navigators based on Chromium) blocking the uploading of a file, when this file is on Google Drive. For some reason, Chrome wrongly believing that the file has been modified between the moment where the user select the file on is device and the moment aftewards where the form in which the file is involved is submitted. The resulting error in the console is "net::err_upload_file_changed." The workaround is to copy the content of the file in a buffer, has explained here : Attached from google drive(cloud storage) in android File gives: err_upload_file_changed error

Lastex answered 12/1 at 14:9 Comment(0)
S
-1

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.

Soriano answered 23/5, 2019 at 14:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.