2017-10-16 27 views
0

我試圖實現自定義休息客戶端構建上的簡單獲取。 如果收到401-403響應,它必須「重定向」應用程序到登錄頁面。authClient不與AUTH_ERROR調用

根據文檔,如果收到401-403錯誤,它會奇蹟般地調用authClient與AUTH_ERROR,但它不會。

有人可以解釋,如何連接它?

我試圖從組件調用REST客戶端:它是「simpleRestClient」

componentDidMount() { 
     restClient(CREATE, 'api/method', { 
    CurrentTime: new Date() 
      })   
      .then(o => 
     { 
    this.setState({ Msg: Object.values(o.data.ServerTime) }); 
      }); 

    } 

RESTClient實現實現簡單的重新實現:

export const fetchJson = (url, options = {}) => { 

const requestHeaders = 
    options.headers || 
    new Headers({ 
     Accept: 'application/json', 
    }); 

if (
    !requestHeaders.has('Content-Type') && 
    !(options && options.body && options.body instanceof FormData) 
) { 
    requestHeaders.set('Content-Type', 'application/json'); 
} 
if (options.user && options.user.authenticated && options.user.token) { 
    requestHeaders.set('Authorization', options.user.token); 
} 

return fetch(url, { ...options, headers: requestHeaders }) 
    .then(response => 
     response.text().then(text => ({ 
      status: response.status, 
      statusText: response.statusText, 
      headers: response.headers, 
      body: text, 
     })) 
    ) 
    .then(({ status, statusText, headers, body }) => { 


     if (status < 200 || status >= 300) { 
      return Promise.reject(
       new HttpError(
        (json && json.message) || statusText, 
        status, 
        json 
       ) 
      ); 
     } 
     let json; 
     try { 
      json = JSON.parse(body); 
     } catch (e) { 
      // not json, no big deal 
     } 
     return { status, headers, body, json }; 
    }); 
}; 


const httpClient = (url, options = {}) => { 
    if (!options.headers) { 
     options.headers = new Headers({ Accept: 'application/json' }); 
    } 
    return fetchJson(url, options); 
} 
+0

你可以分享你的restClient和authClient的代碼嗎? – Gildas

回答

0

你試過拒絕與Error而非承諾一個HttpError