2017-01-23 42 views
1

我正在爲簡單的react/redux應用程序對auth層進行建模。在服務器端,我有一個基於devise_token_auth寶石的API。從提取中提取JSON和頭文件()

我使用fetch在要求張貼標誌:

const JSON_HEADERS = new Headers({ 
    'Content-Type': 'application/json' 
}); 

export const postLogin = ({ email, password }) => fetch(
    `${API_ROOT}/v1/auth/sign_in`, { 
    method: 'POST', 
    headers: JSON_HEADERS, 
    body: JSON.stringify({ email, password }) 
}); 

// postLogin({ email: '[email protected]', password: 'whatever' }); 

這工作,我也得到一個200響應,所有我需要的數據。我的問題是,信息被分爲響應正文和標題。

  • 主體:用戶信息
  • 頭:訪問令牌,過期等

我可以解析JSON體是這樣的:

postLogin({ '[email protected]', password: 'whatever' }) 
    .then(res => res.json()) 
    .then(resJson => dispatch(myAction(resJson)) 

但隨後myAction不會從頭文件中獲取任何數據(解析JSON時丟失)。

有沒有辦法從fetch請求中獲取標題和正文? 謝謝!

回答

1

我想我會分享我們終於解決了這個問題的方式:只需添加在.then鏈中的步驟(解析JSON之前)來解析AUTH頭並分派適當的措施:

fetch('/some/url') 
    .then(res => { 
    const authHeaders = ['access-token', 'client', 'uid'] 
     .reduce((result, key) => { 
     let val = res.headers.get(key); 
     if (val) { 
      result[key] = val; 
     } 
     }, {}); 
    store.dispatch(doSomethingWith(authHeaders)); // or localStorage 
    return res; 
    }) 
    .then(res => res.json()) 
    .then(jsonResponse => doSomethingElseWith(jsonResponse)) 

還有一個辦法,通過強大的丹·阿布拉莫夫(http://stackoverflow.com/a/37099629/1463770

fetch('/some/url') 
    .then(res => res.json().then(json => ({ 
    headers: res.headers, 
    status: res.status, 
    json 
    })) 
.then({ headers, status, json } => goCrazyWith(headers, status, json)); 
啓發

HTH

0

可能是這樣的:

postLogin({ '[email protected]', password: 'whatever' }) 
    .then(res => { 
    processHeader(res.headers.raw()) 
    dispatch(myAction(res.json())) 
    }) 
+0

嗨,謝謝你的回答。不幸的是,自從res.json()返回一個參數以來,'myAction'需要承諾作爲參數。我們希望將簡單的數據傳遞給非thunk動作創建者。 – nerfologist