问题
I made a server query via an app developed using react-native. I used fetch API and it turns out any query with authorization header not working. POST and GET method REQUESTS that don't expect Authorization headers at the server side works well. Some Queries at the server side are protected with authorization and when I make such queries including authorization header, I always get '401:unauthorized' error. But such queries works well with POSTMAN. Any suggestions here would be of great help.
getThingsApi() {
let uri = "https://example.com/things/";
let req = {
method: "GET",
credentials: "include",
//mode: "no-cors",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
//'Access-Control-Request-Method': 'GET',
//'Access-Control-Request-Headers': 'origin, x-requested-with',
'Origin': '',
'Host':'example.com',
'authorization': 'Basic '+Base64.btoa('aaa:bbb'),
'Cache-Control': 'no-cache'
}
};
fetch(uri, req)
.then(response => response.json())
.then(responseJson => {
console.log("ResponseAxis::" + JSON.stringify(responseJson));
console.log("ResponseAxis::" + JSON.stringify(responseJson));
alert("ResponseAxis::" +JSON.stringify(responseJson));
})
.catch(error => {
console.log("Error::" + JSON.stringify(error));
});
}
回答1:
Issue is fixed. We used Fetch API and fetch Api converts all headers into lower-case(eg: authorization) and the server side expects upper-case starting letter(eg: Authorization). After changing the server side code to be case-insensitive, everything works fine.
来源:https://stackoverflow.com/questions/58144396/react-native-fetch-authorization-header-not-working