2017-01-23 1 views
1

간단한 반응식/저가형 애플리케이션의 인증 레이어 모델링입니다. 서버 측에서 나는 devise_token_auth 보석을 기반으로 한 API를 가지고 있습니다. 내가 요청에 사인을 게시 fetch을 사용하고fetch()에서 JSON과 헤더를 모두 추출합니다.

는 :

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

가 나는 우리가 마지막으로이 문제를 해결하는 방법을 공유하고자합니다

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

은 다음과 같이 할 수있다 : 단지합니다 (JSON을 파싱 전) .then 체인의 단계를 추가하여 인증 헤더를 구문 분석 :

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

안녕하세요, 귀하의 답변에 감사드립니다. 불행히도'myAction'은 res.json()이 하나를 반환하기 때문에 약속으로 받아 들여야합니다. 비 썽크 액션 크리에이터에게 일반 데이터를 전달하고 싶습니다. – nerfologist

관련 문제