program tip

Angular의 실제 오류 메시지 대신 "(unknown url) : 0 Unknown Error"에 대한 Http 실패 응답이 나타납니다.

radiobox 2020. 9. 6. 09:18
반응형

Angular의 실제 오류 메시지 대신 "(unknown url) : 0 Unknown Error"에 대한 Http 실패 응답이 나타납니다.


Angular 4 HttpClient사용하여 외부 서비스에 요청을 보냅니다. 매우 표준적인 설정입니다.

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

문제는 요청이 실패하면 Http failure response for (unknown url): 0 Unknown Error콘솔에 일반 메시지가 표시된다는 것입니다. 한편 크롬에서 실패한 요청을 살펴보면 응답 상태가 422임을 알 수 있으며 "미리보기"탭에서 실패 원인을 설명하는 실제 메시지를 볼 수 있습니다.

크롬 개발 도구에서 볼 수있는 실제 응답 메시지에 어떻게 액세스합니까?

다음은 문제를 보여주는 스크린 샷입니다. 여기에 이미지 설명 입력


문제는 CORS 와 관련이 있습니다. Chrome 콘솔에 또 다른 오류가 있음을 발견했습니다.

요청 된 리소스에 'Access-Control-Allow-Origin'헤더가 없습니다. 따라서 원본 ' http : // localhost : 4200 '은 액세스가 허용되지 않습니다. 응답에 HTTP 상태 코드 422가 있습니다 .`

이는 Access-Control-Allow-Origin백엔드 nginx가 add_header지시문 을 사용하여 응답에 해당 헤더를 추가하도록 구성되었지만 백엔드 서버의 응답에 헤더 가 없음을 의미합니다 .

그러나이 지시문은 응답 코드가 20X 또는 30X 인 경우에만 헤더를 추가합니다. 오류 응답에서 헤더가 누락되었습니다. always응답 코드에 관계없이 헤더가 추가되었는지 확인 하기 위해 매개 변수 를 사용해야했습니다 .

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

백엔드가 올바르게 구성되면 Angular 코드의 실제 오류 메시지에 액세스 할 수 있습니다.


크롬에서 광고 차단 확장 프로그램을 끈 후 나를 위해 일하면 브라우저에서 http를 차단하는 것이 있기 때문에이 오류가 나타납니다.

여기에 이미지 설명 입력


다른 사람이 나처럼 길을 잃은 경우 ... 내 문제는 CORS로 인한 것이 아닙니다 (내가 서버를 완전히 제어하고 CORS가 올바르게 구성되었습니다!).

내 문제는 기본적으로 일반 텍스트 네트워크 통신비활성화 하는 Android 플랫폼 레벨 28을 사용 하고 있고 내 랩톱의 IP (API 서버를 실행하는)를 가리키는 앱을 개발하려고했기 때문입니다. API 기본 URL은 http : // [LAPTOP_IP] : 8081 과 유사 합니다. https 가 아니기 때문에 android webview는 내 노트북의 전화 / 에뮬레이터와 서버 사이의 네트워크 xfer를 완전히 차단합니다. 이 문제를 해결하려면 :

네트워크 보안 구성 추가

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


If U guys are using .net core application below the step might be help to you!

MoreOver this is not Angular or other request error in your FrontEnd application

First u guys have to add the Microsoft CORS package from Nuget. If your guys are not added in your application, follow the installation command.

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 you need to 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 extras 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.

Thanks you sathish(sat)


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.


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.


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"

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.


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.


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.


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.


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.


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(',');
        }
    }
};

내 오류는 파일이 너무 크다는 것입니다 (dotnet 코어에는 @ ~ 25Mb 제한이있는 것 같습니다). 환경

  • web.config의 maxAllowedContentLength에서 4294967295 (uint의 최대 값)로
  • [DisableRequestSizeLimit]로 컨트롤러 액션 꾸미기
  • services.Configure (옵션 => {options.MultipartBodyLengthLimit = 4294967295;}); Startup.cs에서

나를 위해 문제를 해결했습니다.


여기에서 모든 의견을 찾은 후에도 동일한 오류가 발생했지만 도움이되지 않았습니다. 마지막으로 내 노드 서버가 실행되고 있지 않다는 것이 나옵니다.

참고 URL : https://stackoverflow.com/questions/47180634/i-get-http-failure-response-for-unknown-url-0-unknown-error-instead-of-actu

반응형