Reputation: 3958
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:
Upvotes: 185
Views: 527214
Reputation: 970
This error was fixed for me
In the way that the data I was sending to the server
One of the values of this model was a very large object in the form of a repeating tree
That the server did not need this data
Before sending the data to the server, I deleted this value that was in the form of a tree and this problem was solved for me
Now before sending to the server the relatedTaskIds
value is empty and then sent
if (this.form.valid) {
const model = { ...this.form.value, relatedTaskIds: [] }
if (this.dataEdit) {
this.service.put(this.dataEdit.id, model).subscribe(x => {
this.showSuccessMessage();
this.ref.close(x);
})
} else {
this.service.post(model).subscribe(x => {
this.showSuccessMessage();
this.ref.close(x);
})
}
}
Upvotes: 0
Reputation: 13
First check in Postman if you are still getting the same error?
If yes, then the reason must be you might be using http instead of https. I found out this was the issue in my case.
for eg-
http://localhost:7269/api/categories (Earlier, which caused error)
https://localhost:7269/api/categories (Now)
Upvotes: 0
Reputation: 31
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
Upvotes: 0
Reputation: 21
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
Installing django-cors-headers. Do this by using pip
pip install django-cors-headers
Adding cors-headers to installed apps in /settings.py
INSTALLED_APPS = [ 'rest_framework', 'corsheaders' ]
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
Upvotes: 0
Reputation: 891
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
Upvotes: 1
Reputation: 624
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.
Upvotes: 1
Reputation: 7067
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 ...">
Upvotes: 0
Reputation: 145
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.
Upvotes: 1
Reputation: 2071
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
}));
Upvotes: 1
Reputation: 269
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);
}
}
Upvotes: 0
Reputation: 59
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
Upvotes: 1
Reputation: 6922
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.
Upvotes: 2
Reputation: 7165
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();
});
Upvotes: 5
Reputation: 481
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");
Upvotes: 1
Reputation: 571
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)
Upvotes: 0
Reputation: 359
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.
Upvotes: 22
Reputation: 6862
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(',');
}
}
};
Upvotes: 4
Reputation: 4173
My error was that the file was too large (dotnet core seems to have a limit @~25Mb). Setting
solved the problem for me.
Upvotes: -1
Reputation: 753
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:
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.
<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
Upvotes: 44
Reputation: 2837
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.
Upvotes: 7
Reputation: 146180
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.
Upvotes: 2
Reputation: 27485
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.
Upvotes: 4
Reputation: 6933
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.
Upvotes: 1
Reputation: 973
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.
Upvotes: 0
Reputation: 646
working for me after turn off ads block extension in chrome, this error sometime appear because something that block http in browser
Upvotes: 18
Reputation: 486
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.
Upvotes: 0
Reputation: 443
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.
Upvotes: 5
Reputation: 45
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"
Upvotes: 1
Reputation: 3958
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.
Upvotes: 142