gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:52:31 26 4
gpt4 key购买 nike

我正在从函数进行 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com