作为对象的一部分发送时无法读取response.json()

时间:2018-10-25 11:40:33

标签: javascript json reactjs react-native http-post

我正在从函数和return response.json()进行API调用,在调用函数上可以获取数据。但是,与response.json()一起,我还需要将header数据传递给调用函数,因此我创建了一个对象,并向其中添加了response.json()和标头数据。

在调用函数中,我可以读取header数据,但不能读取response.json()。您能建议一下如何正确读取响应数据吗?

API调用功能

export function loginlibAPI ( id, password ){
    var loginURL = 'https://example.com/sessions';
    return fetch(loginURL, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            "user": {
                'email': id,
                'password': password
            }            
        }),
    })
    .then((response) =>{
          consoleLog('loginUser_lib - header ' + response.headers.get('Authorization-X'));  

    if (response.headers.get('content-type').match(/application\/json/)) {
        consoleLog('inside content type');        
        //return response.json(); // works 
        return { response: response.json(), authorizationToken: response.headers.get('Authorization-X') }; //can not read the response in the calling function
    }
    return response;
    })
    .catch((error) => {
        consoleLog('Error from loginlibAPI() api call - ' + error.message);
    });
}

调用功能

loginUser_lib = async (  ) => {
    const returned = await loginlibAPI( this.state.nationalId, this.state.password ).then((res) => {
      //consoleLog('loginUser_lib - '  + JSON.stringify(res)); // can read data when only response.json() is sent
      consoleLog('loginUser_lib - ' + res.authorizationToken); //works fine - received 'abcdfdlkjsdlkjsdlkj'
      consoleLog('loginUser_lib - ' + res.response);  //returns - [object Object]
      consoleLog('loginUser_lib - ' + JSON.stringify(res.response)); //returns - {"_40":0,"_65":0,"_55":null,"_72":null}
    })
  }

1 个答案:

答案 0 :(得分:1)

请记住,response.json()返回一个承诺,因此您需要先解决它,然后才能从中获取数据。像这样:

return response
    .json()
    .then(data => ({
        response: data,
        authorizationToken: response.headers.get('Authorization-X')
    });