私のReactアプリでは、サーバー側からいくつかのチャートデータを取得するためにfetchを使用しています。 以下に示すように、関数fetchDataは、チャートデータをjson形式で取得する役割を担います。 Chromeのネットワークパネルで通話が成功したことがわかります。プロミスからレスポンス本文を取得するにはどうすればいいですか?
function fetchData() {
let token;
if (sessionStorage.bearerToken) {
token = `Bearer ${sessionStorage.bearerToken}`;
}
console.log('the token is', token);
const config = {};
config.method = 'GET';
config.headers = {
'Content-Type':'application/json',
'Authorization':token
};
const req = new Request(webConfig.ReqURL.fetchChartsData, config);
// return fetch(`${config.base}dashboard_charts.json`)
return fetch(req)
.then((response) => {
return response;
});
}
function * getData (action) {
try {
// const charts = yield call(fetchData);
const resp = yield apiCall(fetchData);
const charts = resp.then((resp) => { return resp.json(); });
console.log('the charts....', charts);
yield put({ type: UPDATE_DASHBOARD_CHART, charts: charts });
} catch (error) {
yield put({ type: UPDATE_DASHBOARD_CHART, charts: [] });
}
}
http応答のステータスコードを確認する必要があります。ステータスコードが403の場合、ログオンフローにリダイレクトするにはアプリが必要です。だから、の代わりに apiCall(fetchData)を使用しています(fetchData)を直接呼び出しています。
export function* apiCall(fn, ...rest) {
const response = yield call(fn, ...rest);
const status = response.status;
console.log('~~ status', status);
if(status === 419) { //419: When the session has expired
yield put(sessionExpired());
}
if(status === 403) { //403: When the resource is forbidden
// yield put(resourceForbidden());
yield auth();
return Promise.reject(response);
}
if(status === 401) { //401: When the resource is unauthorized
yield put(resourceUnauthorized());
}
return response;
}
上記のコードスニペットは、佐賀のapiCallの実装です。応答コードが期待どおりに403であれば、認証フローを起動できます。
しかし、私はケース200のレスポンスを処理する方法がわかりません。プロミスが返されるのがわかりますが、getData関数でconsole.logに何も表示されません。
私のコードで何が問題なのか分かりますか?