[英]“Unhandled rejection” error in Aurelia Fetch Client
我使用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);
}
}
然后通过以下代码从另一个代码中调用方法getData()
:
dataService.getData().then(data => {
this.data = data;
}).catch(error => {
this.backendError = true;
});
如您所见,我在这里使用catch
语句,并在发生错误的情况下调用它,但是在控制台中,我还看到来自库的错误消息:“ vendor-bundle.js:1395未处理的拒绝TypeError:无法获取 ” 。 我该如何摆脱呢?
我不确定这是否是Aurelia HTTP Fetch Client的错误,但是添加responseError
拦截器应删除控制台中的Unhandled Exception警告。
let http = new HttpClient();
http.configure(config => {
config.withInterceptor({
response(response) {
return response;
},
responseError(error) {
return error;
}
})
});
此错误也可能来自.NET Core API中的UseDeveloperExceptionPage
中间件。 该中间件从响应中剥离所有标头,这些响应会导致CORS问题,并导致您看到的“ TypeError:无法提取”错误。 这里是我的解决方案,这是完全描述的例子在这里 。
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);
}
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.