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

标签 javascript json reactjs react-native http-post

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

在调用函数中,我可以读取 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}
    })
  }

最佳答案

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

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

关于javascript - 作为对象的一部分发送时无法读取 response.json(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52988430/

相关文章:

reactjs - 使用react-icons时导入错误

javascript - 使用 Vue 和 HTML 在 JavaScript 中制作幻灯片,但图像出现错误 404 "Not found"

javascript - 链接检查正则表达式

javascript - 使用 AJAX 删除项目时如何重新加载 jQuery Masonry?

javascript - 如何包含来自另一个 php 文件的 php 验证函数

mysql - MySQL 中的二进制/字符串转换

javascript - 类型错误 : Cannot read properties of null (reading 'useState' ) in Next. js

javascript - 将对象推送到数组时 ng-repeat 不更新

JSON Postman 正文不适用于 PostgreSQL 插入

javascript - 如何在纯 React JS 中延迟组件卸载事件(没有 React Router)?