Я делаю вызов API из функции и return response.json()
, для вызывающей функции я могу получить данные.Но наряду с response.json () мне также нужно передать header
данные вызывающей функции, поэтому я создал объект и добавил к нему response.json () и данные заголовка.
В вызывающей функции Iможет читать 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}
})
}