2016-09-09 4 views
1

私はAureliaを使用して作成しているアプリケーションがあります。私はhttp応答を簡素化したいと思う。Aurelia http-fetch handle error

私は次のコードを解除している:

@inject(HttpClient) 
export class Api { 
    constructor(httpClient) { 
    this.http = httpClient; 
    this.http.configure(config => { 
     config 
     .withBaseUrl(window.sessionStorage.getItem('baseUrl')) 
     .withDefaults({ 
      headers: { 
      'Accept': 'application/json', 
      'X-Requested-With': 'Fetch' 
      } 
     }) 
     .withInterceptor({ 
      request: handleRequest, 
      response: handleResponse 
     }); 
    }) 
    } 

    get(url, params) { 
    return this.http.fetch(url, {method: 'get', body: params}); 
    } 

    post(url, params) { 
    return this.http.fetch(url, {method: 'post', body: params}); 
    } 
} 

function handleResponse(response) { 
    if (!response.ok) { 
    thown {status: response.status, data: rsponse.json() };//this not works 
    } 
    return response.json(); 
} 

function handleRequest(request) { 
    let token = window.sessionStorage.getItem('token'); 
    if (token) { 
    request.headers.append('Authorization', `bearer ${token}`); 
    } 
    return request; 
} 

response.okfalse応答結果です:

Object { status: 422, data: Promise } 

がどのように私はこの問題を解決することができますか?

答えて

0

返されたオブジェクトからデータが欠落し、Promiseがエラーで返されるという問題があると仮定すると、json()から返された約束が最初に解決されるまで待つ必要があります。以下のような何か:

if (!response.ok) { 
 
    response.json().then(data => { 
 
    return {status: response.status, data: data}; 
 
    } 
 
}