我有一个使用Aurelia创建的应用程序。我希望简化http响应。
我有以下代码:
@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.ok
为false
时,响应结果为:
Object { status: 422, data: Promise }
我该如何解决这个问题?
答案 0 :(得分:0)
假设您的问题是返回的对象中缺少数据并且错误时返回了Promise,那么您将需要等待从json()返回的promise才能首先解析。类似的东西:
if (!response.ok) {
response.json().then(data => {
return {status: response.status, data: data};
}
}