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:
Patrick
17.6k6 gold badges70 silver badges84 bronze badges
asked Nov 8, 2017 at 13:10
7
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.
answered Nov 14, 2017 at 21:06
grdlgrdl
3,6003 gold badges20 silver badges25 bronze badges
9
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
answered May 17, 2019 at 0:43
haggyhaggy
7336 silver badges11 bronze badges
5
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.
Feasoron
3,4422 gold badges23 silver badges34 bronze badges
answered Mar 22, 2019 at 6:40
sathishsathish
2902 silver badges14 bronze badges
0
working for me after turn off ads block extension in chrome, this error sometime appear because something that block http in browser
answered Aug 29, 2018 at 15:38
DwiyiDwiyi
6287 silver badges17 bronze badges
1
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.
answered Feb 21, 2018 at 9:56
PerrierPerrier
2,7435 gold badges33 silver badges53 bronze badges
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.
answered Apr 26, 2018 at 13:04
fraxfrax
4434 silver badges10 bronze badges
2
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();
});
answered Feb 20, 2020 at 14:32
FistOfFuryFistOfFury
6,7077 gold badges49 silver badges57 bronze badges
1
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.
answered Dec 5, 2018 at 12:54
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(',');
}
}
};
answered Sep 9, 2019 at 21:33
Marcos DimitrioMarcos Dimitrio
6,5465 gold badges38 silver badges61 bronze badges
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.
answered Dec 6, 2018 at 22:05
Simon_WeaverSimon_Weaver
139k82 gold badges640 silver badges684 bronze badges
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.
answered Mar 1, 2020 at 19:23
Shahin DohanShahin Dohan
5,9893 gold badges39 silver badges58 bronze badges
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"
answered Feb 2, 2018 at 13:31
3
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.
answered Nov 6, 2018 at 19:50
N-ateN-ate
5,8632 gold badges40 silver badges47 bronze badges
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");
answered Jan 2, 2020 at 17:49
0
if you are using nodejs as backend, here are steps to follow
-
install cors in your backend app
npm install cors
-
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 }));
answered Feb 14, 2021 at 17:59
YouBeeYouBee
1,94115 silver badges16 bronze badges
answered Dec 7, 2022 at 7:34
SnaketecSnaketec
3821 silver badge14 bronze badges
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.
answered Aug 17, 2018 at 11:06
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.
answered Sep 1, 2018 at 14:03
J.Kirk.J.Kirk.
9433 gold badges12 silver badges32 bronze badges
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)
answered Nov 14, 2019 at 11:16
Luis LopezLuis Lopez
5511 gold badge10 silver badges28 bronze badges
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
answered Apr 15, 2020 at 11:55
dgncndgncn
495 bronze badges
1
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);
}
}
answered Nov 12, 2020 at 4:55
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.
answered Apr 28, 2022 at 7:40
KrithikaKrithika
1151 silver badge10 bronze badges
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 ...">
answered Jul 13, 2022 at 18:25
Jeb50Jeb50
6,1686 gold badges47 silver badges84 bronze badges
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.
answered Aug 19, 2022 at 2:13
KenFKenF
5344 silver badges14 bronze badges
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.
answered May 23, 2019 at 14:35
SpikolynnSpikolynn
4,0392 gold badges37 silver badges44 bronze badges
The «Http failure response for (unknown URL): 0 Unknown Error» is a common error that occurs in Angular 4 while making HTTP requests. This error usually appears when the server is unable to process the request and returns a 0 status code. This can be due to various reasons such as an incorrect API endpoint, network connectivity issues, or CORS policies. To fix this issue, there are several methods that can be tried, including:
Method 1: Check API endpoint
To fix the «Http failure response for (unknown URL): 0 Unknown Error» issue in Angular 4, you can use the «Check API endpoint» method. This method involves checking the API endpoint to ensure that it is working correctly. Here are the steps to follow:
- Import the HttpClient module in your component:
import { HttpClient } from '@angular/common/http';
- Inject the HttpClient module in your component’s constructor:
constructor(private http: HttpClient) { }
- Create a method to check the API endpoint:
checkApiEndpoint() {
const url = 'https://your-api-endpoint.com';
this.http.get(url).subscribe(
res => {
console.log('API endpoint is working!');
},
err => {
console.log('API endpoint is not working!');
}
);
}
- Call the checkApiEndpoint() method in your component’s ngOnInit() method:
ngOnInit() {
this.checkApiEndpoint();
}
By checking the API endpoint in this way, you can determine whether the issue is with the endpoint or with your Angular code. If the API endpoint is working correctly, then you may need to check your Angular code to see if there are any issues. If the API endpoint is not working, then you may need to contact the API provider to resolve the issue.
Method 2: Configure CORS policy
How to fix Angular 4: «Http failure response for (unknown URL): 0 Unknown Error» with «Configure CORS policy»
- Install the
cors
package in your backend server. This package will allow CORS requests from your Angular application.
- Import the
cors
package in your backend server file.
const cors = require('cors');
- Use the
cors
middleware in your backend server file.
- Configure the
HttpClient
in your Angular application to send CORS requests.
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule,
],
})
export class AppModule {}
- Send a CORS request in your Angular service file.
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(private http: HttpClient) {}
getData() {
return this.http.get('http://localhost:3000/data');
}
}
- Test your application to ensure that the «Http failure response for (unknown URL): 0 Unknown Error» issue has been resolved.
That’s it! By configuring the CORS policy, you have allowed your Angular application to send requests to your backend server.
Method 3: Debug Network Connectivity Issues
If you are encountering the «Http failure response for (unknown URL): 0 Unknown Error» error in Angular 4, it is likely that there is an issue with the network connectivity. In this tutorial, we will go over how to debug network connectivity issues in Angular 4 to fix this error.
Step 1: Check the Network Connection
The first step to debugging network connectivity issues is to check the network connection. To do this, we can use the navigator.onLine
property to determine if the browser is connected to the internet. We can add this check to our app.component.ts
file as follows:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: '<router-outlet></router-outlet>'
})
export class AppComponent {
constructor() {
if (!navigator.onLine) {
console.log('No internet connection');
}
}
}
Step 2: Check the API URL
If the network connection is not the issue, then the next step is to check the API URL. It is possible that the URL is incorrect or the API is down. We can use the HttpClient
module in Angular to make a request to the API and check the response.
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
template: '<router-outlet></router-outlet>'
})
export class AppComponent {
constructor(private http: HttpClient) {
this.http.get('https://api.example.com/data').subscribe(
data => console.log(data),
error => console.log(error)
);
}
}
In the above example, we are making a request to https://api.example.com/data
using the HttpClient
module. We are subscribing to the response and logging the data and error to the console.
Step 3: Check the CORS Settings
If the API URL is correct and the network connection is not the issue, then the next step is to check the CORS settings. It is possible that the API is not configured to allow requests from your domain.
To check the CORS settings, we can use a browser extension such as CORS Everywhere. This extension allows us to bypass the CORS restrictions and make requests to the API. If the request is successful with the extension enabled, then the issue is with the CORS settings.
Method 4: Check for HttpClientModule Import
To fix the «Http failure response for (unknown URL): 0 Unknown Error» in Angular 4, you can check whether the HttpClientModule is imported correctly or not. Here are the steps to do it:
- Open the app.module.ts file.
- Import the HttpClientModule from ‘@angular/common/http’.
- Add the HttpClientModule to the imports array.
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
- In the component where you are making the HTTP request, import the HttpClient from ‘@angular/common/http’.
- Inject the HttpClient in the constructor.
- Use the HttpClient to make the HTTP request.
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
template: `
<div>{{ response }}</div>
`
})
export class AppComponent {
response: string;
constructor(private http: HttpClient) {}
ngOnInit() {
this.http.get('https://jsonplaceholder.typicode.com/posts/1').subscribe((data) => {
this.response = data['title'];
});
}
}
By following these steps, you can fix the «Http failure response for (unknown URL): 0 Unknown Error» in Angular 4 by checking for HttpClientModule import.
Method 5: Use a try-catch block
To fix the «Http failure response for (unknown URL): 0 Unknown Error» error in Angular 4, we can use a try-catch block. Here’s an example code snippet:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getData() {
try {
return this.http.get('https://example.com/api/data').pipe(
catchError(error => {
console.error('Error:', error);
return throwError('Something went wrong');
})
);
} catch (error) {
console.error('Error:', error);
return throwError('Something went wrong');
}
}
}
In this example, we have a DataService
class that uses the HttpClient
to make a GET request to an API endpoint. We wrap the http.get
method in a try-catch block to catch any errors that may occur.
If an error occurs, we log the error to the console and return a new Observable
that emits an error message. We use the catchError
operator from the rxjs/operators
module to handle the error and return a new Observable
.
By using a try-catch block, we can catch any errors that occur during the HTTP request and handle them appropriately.
Answer by Kyng Alvarez
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.
– Manohar Reddy Poreddy
May 18 ’19 at 7:27
,That’s it! From there I rebuilt the APK and the app was now able to communicate from both the emulator and phone.,In asp.net core, If your api controller doesn’t have annotation called [AllowAnonymous], add it to above your controller name like,A similar error can occur, when you didn’t give a valid client certificate and token that your server understands:
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>
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>
Answer by Colt Yates
Error with
status: 0
statusText: «Unknown Error»
url: null
also occurs when browser doesn’t have internet connection., user.ts:46 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: «Unknown Error», url: null, ok: false, …} error : ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: «error», …} headers : HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)} message : «Http failure response for (unknown url): 0 Unknown Error» name : «HttpErrorResponse» ok : false status : 0 statusText : «Unknown Error» url : null __proto__ : HttpResponseBase,Maybe some others have the same problem I had. https://stackoverflow.com/questions/48557390/angular-4-http-failure-response-for-unknown-url-0-unknown-error,Hello, we reviewed this issue and determined that it doesn’t fall into the bug report or feature request category. This issue tracker is not suitable for support requests, please repost your issue on StackOverflow using tag angular.
user.ts:46 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …} error : ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …} headers : HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)} message : "Http failure response for (unknown url): 0 Unknown Error" name : "HttpErrorResponse" ok : false status : 0 statusText : "Unknown Error" url : null __proto__ : HttpResponseBase
user.ts:46 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …} error : ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …} headers : HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)} message : "Http failure response for (unknown url): 0 Unknown Error" name : "HttpErrorResponse" ok : false status : 0 statusText : "Unknown Error" url : null __proto__ : HttpResponseBase
Answer by Skyler Howe
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.,add_header ‘Access-Control-Allow-Origin’ ‘http://localhost:4200’ always;
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>
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>
Answer by Jaylah Sutton
I’m using Ionic v6.11.8 and created an App using Angular,
The app is working fine on browser, But when I build a debug app from it im getting Http failure response for (unknown url): 0 Unknown Error for «few» endpoints.,Tried googling the issue and tried many solutions from the results, but nothing worked till now. Even I switched t @ionic-native/http/ngx module, then I cant test the app on browser.,But this issue is not happening with all API endpoints, Most of the endpoints are working fine. Only 1-2 Endpoints happening like this, I thought there must be any error from server side, but no. there are no errors.,I mean, I have around 5-6 API calls, most of them are working fine, for few, I’m getting error. I’m using WordPress on server and created API using WordPress RESTful API and All of the API endpoints are working fine on browser. I’m using Angular HttpClient to make HTTP calls.
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
<domain includeSubdomains="true">my-website.com</domain>
</trust-anchors>
</base-config>
</network-security-config>
Answer by Ruth Lowery
To solve this issue you need to follow thos below script.,
How to freeze rows and columns at the same time in excel 2013.
,
the instanceof operator enables to discover the type of object it was invoked upon.
Code:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<!-- Set application-wide security config -->
<base-config cleartextTrafficPermitted="true"/>
</network-security-config>
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<!-- Set application-wide security config -->
<base-config cleartextTrafficPermitted="true"/>
</network-security-config>
<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>
<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>
Install-Package Microsoft.AspNetCore.Cors
Install-Package Microsoft.AspNetCore.Cors
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
app.UseCors( options =>
options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseMvc();
}
Answer by Lennon Trejo
Error with
status: 0
statusText: “Unknown Error”
url: null
also occurs when browser doesn’t have internet connection.,
Anonymous says:
March 31, 2020 at 2:47 am
Error with
status: 0
statusText: “Unknown Error”
url: null
also occurs when browser doesn’t have internet connection.
No CORS error object should be differentiable from error of No Internet connection.
,Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
,Status code 0 indicates a CORS failure.
user.ts:46 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …} error : ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …} headers : HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)} message : "Http failure response for (unknown url): 0 Unknown Error" name : "HttpErrorResponse" ok : false status : 0 statusText : "Unknown Error" url : null __proto__ : HttpResponseBase
user.ts:46 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …} error : ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …} headers : HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)} message : "Http failure response for (unknown url): 0 Unknown Error" name : "HttpErrorResponse" ok : false status : 0 statusText : "Unknown Error" url : null __proto__ : HttpResponseBase
I have the following Authentication and Login service in Angular 6:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class AuthApiService {
public credentials:any=[];
constructor(private http: HttpClient) { }
login(username, password)
{
let headerOptions = new HttpHeaders();
headerOptions.append('Content-Type', 'application/json');
headerOptions.append("authorization", "basic aGM0YXBwOmHjddP5NjU=");
let test = {user: username, pass: password};
this.credentials = JSON.stringify(test);
console.log("hi "+ this.credentials);
return this.http.post('https://127.0.0.1/api/scripts/login.php', this.credentials, {
headers: headerOptions
}).pipe(map(
res=>{
console.log(res)
},
err=>
console.log(err)
))
}
}
And when I click on Login Button:
a id="btn-login" (click)="login()" class="btn btn-success">Login </a>
A function in login.component.ts will execute the login function of the Authentication service:
login(){
this.auth.login("a", "p").subscribe(
(data)=>{
console.log(data)
},
(error)=>{
console.log(error)
}
)
}
In php, and for the url, I am running it in the browser and I can see the result properly 1
, but there is an error at the console when I click on the button:
«Http failure response for (unknown url): 0 Unknown Error»
At the network tab:
The PHP script:
Lets start with the main class:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS');
header('Access-Control-Allow-Headers: *');
error_reporting(E_ALL);
class api {
private $username ="...";
private $password ="...";
private $db="...";
private $host = "...";
public $conn;
//Connection
public function connection(){
try{
$this->conn = new PDO("mysql:host=$this->host;dbname=$this->db", $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->conn->exec("SET CHARACTER SET utf8");
return $this->conn;
}
catch(PDOException $e){
return $e->getMessage();
}
}
//Login
public function login($conn, $user){
$login = "SELECT username FROM login WHERE username=:user LIMIT 1";
$execLogin = $this->conn->prepare($login);
$execLogin->bindValue(":user", $user);
$execLogin->execute();
$res = $execLogin->rowCount();
return $res;
// if($res>0)
// {
// return json_encode($res);
// }
// else{
// echo 0;
// }
}
}
?>
And then, the login function is executed (https://127.0.0.1/api/scripts/login.php
):
<?php
header('Content-Type: application/json');
require_once('../api.php');
//Getting username and password from Ionic
$user="brital";
$pass = json_decode($_POST['credentials']);
$newApi = new api();
$conn = $newApi->connection();
$res = $newApi->login($conn, $user);
echo $res;
?>
Issue
I am trying to send a GET request from my angular app to my .NET Core WebAPI backend. Both are running on localhost. Angular is running on port 4200, WebAPI is running on port 5001. When I make the GET request in Angular, the following error is shown in console:
After searching online, almost every answer comes down to an issue with CORS not being enabled correctly on the backend server. However, to my knowledge, I have CORS setup correctly. Here is my configuration for CORS:
This is the service function in Angular as well as the GET method in WebAPI:
I know the URL is correct, because, when I copy the URL into Postman, it works as intended.
Mainly I’m wondering if I did mess up CORS, because that seems to be the main issue with this error message, or if there is something else I may have missed.
EDIT (Solution):
Ok, so through various trials and errors, I believe I have found the issue. When I made the initial project, I made the project in JetBrains Rider. I decided to try making a new project in Visual Studio to see what would happen, however, the problem still remained. As it turns out the issue was not with CORS, but with an invalid HTTPS localhost certificate. When I tried to run the console command dotnet dev-certs https --trust
I did not get a popup to confirm the certificate, but instead just a generic error message that was not useful. Here is how I fixed the issue (whether or not this is the right way can be for discussion).
- Ran the WebAPI and opened the site in Chrome.
- On HTTPS connections, Chrome will allow you to see the certificate info by clicking the “Secure” or “Not Secure” tag next to the URL. I clicked that and opened the certificate info window.
- There is a tab called “Details” where I was able to save the certificate to my computer.
- Once the certificate was saved, I could right-click it and there was a right-click option called “Install Certificate”.
- I installed the certificate just clicking next and leaving the values as default. After that the Angular app now makes GET, POST, PUT, etc requests as expected, and when I copy the Web API URLs into Chrome, Chrome now says the connection is secure rather than not secure as it was doing before.
Solution
Ok, so through various trials and errors, I believe I have found the issue. When I made the initial project, I made the project in JetBrains Rider. I decided to try making a new project in Visual Studio to see what would happen, however, the problem still remained. As it turns out the issue was not with CORS, but with an invalid HTTPS localhost certificate. When I tried to run the console command dotnet dev-certs https --trust
I did not get a popup to confirm the certificate, but instead just a generic error message that was not useful. Here is how I fixed the issue (whether or not this is the right way can be for discussion).
- Ran the WebAPI and opened the site in Chrome.
- On HTTPS connections, Chrome will allow you to see the certificate info by clicking the “Secure” or “Not Secure” tag next to the URL. I clicked that and opened the certificate info window.
- There is a tab called “Details” where I was able to save the certificate to my computer.
- Once the certificate was saved, I could right-click it and there was a right-click option called “Install Certificate”.
- I installed the certificate just clicking next and leaving the values as default. After that the Angular app now makes GET, POST, PUT, etc requests as expected, and when I copy the Web API URLs into Chrome, Chrome now says the connection is secure rather than not secure as it was doing before.
This is the error I was getting when running dotnet dev-certs https --trust
for reference: