2016-09-09 52 views
1

我有一個應用程序使用Aurelia創建。我希望簡化http響應。Aurelia http-fetch句柄錯誤

我都去下面的代碼:

@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()返回的promise先解析。喜歡的東西:

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