简体   繁体   English

Aurelia Fetch Client中的“未处理的拒绝”错误

[英]“Unhandled rejection” error in Aurelia Fetch Client

I use Aurelia Fetch Client library to fetch JSON data from the backend server by the code: 我使用Aurelia Fetch Client库通过以下代码从后端服务器获取JSON数据:

getData() {
    let httpClient = new HttpClient();

    return httpClient.fetch('http://localhost:9220/get-data')
        .then(response => response.json())
        .then(data => return data);
    }
}

And the metod getData() is called from the another code by the code: 然后通过以下代码从另一个代码中调用方法getData()

dataService.getData().then(data => {
    this.data = data;
}).catch(error => {
    this.backendError = true;
});

As you can see I use here a catch statement and in case of error it's called, but I also see in the console an error message that comes from the library: " vendor-bundle.js:1395 Unhandled rejection TypeError: Failed to fetch ". 如您所见,我在这里使用catch语句,并在发生错误的情况下调用它,但是在控制台中,我还看到来自库的错误消息:“ vendor-bundle.js:1395未处理的拒绝TypeError:无法获取 ” 。 How can I get rid it? 我该如何摆脱呢?

I'm unsure if this is a bug with the Aurelia HTTP Fetch Client, but adding a responseError interceptor should remove the Unhandled Exception warning in the console. 我不确定这是否是Aurelia HTTP Fetch Client的错误,但是添加responseError拦截器应删除控制台中的Unhandled Exception警告。

let http = new HttpClient();

http.configure(config => {
    config.withInterceptor({
        response(response) {
            return response;
        },
        responseError(error) {
            return error;
        }
    })
});

This error may also come from the UseDeveloperExceptionPage middleware in a .NET Core API. 此错误也可能来自.NET Core API中的UseDeveloperExceptionPage中间件。 This middleware strips all headers from the response which create CORS issues and causes the "TypeError: Failed to fetch" error you saw. 该中间件从响应中剥离所有标头,这些响应会导致CORS问题,并导致您看到的“ TypeError:无法提取”错误。 Here is an example of my solution, which is described in full here . 这里是我的解决方案,这是完全描述的例子在这里

.NET Core Middleware .NET核心中间件

private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
    var code = HttpStatusCode.InternalServerError;

    var result = JsonConvert.SerializeObject(new { error = "An internal server error has occurred." });
    context.Response.ContentType = "application/json";
    context.Response.StatusCode = (int)code;
    return context.Response.WriteAsync(result);
}

Aurelia Interceptor 奥雷利亚拦截器

responseError(response: any): Promise<Response> {
    if (response instanceof Response) {
        return response.json().then((serverError: ServerError) => {

             // Do something with the error here.

             return Promise.reject<Response>(serverError.error);
        }); 
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM