How to pass authorization token in header for GET method using XMLHttpRequest in react native - react-native

I am new to react-native. I am trying to pass the authorization token through a header in the GET method. But I am getting an unauthorized error.
I have already tried this code "Using an authorization header with Fetch in React Native" not working for me and also with XMLHttpRequest()
But the API works fine in postman, Java(core) and Android.
Do we have any special implementation in react-native to pass headers?
Could anyone can help me with this?
My code: Changed the server name.
getData() {
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://xyz-test-server.server.com/api/v3/users/details/");
xhr.setRequestHeader("Authorization", "Basic cC5qYWltdXJ1Z2FuLm1jYUBnbWFpbC5jb206MTIzNDU2");
xhr.setRequestHeader("User-Agent", "PostmanRuntime/7.17.1");
xhr.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-1");
xhr.setRequestHeader("Accept", "*/*");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Postman-Token", "d8ae56bf-1926-44e4-9e94-23223234,93a110a2-ee8e-42d5-9f7b-45645ddsfg45");
xhr.setRequestHeader("Accept-Encoding", "gzip, deflate");
xhr.setRequestHeader("Connection", "keep-alive");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
}
Fetch method:
async _getProtectedQuote() {
fetch('https://xyz-test-server.server.com/api/v3/users/details/', {
method: 'GET',
headers: new Headers({
'Authorization': 'Basic cC5qYWltdXJ1Z2FuLm1jYUBnbWFpbC5jb206MTIzNDU2',
'Content-Type': 'application/x-www-form-urlencoded'
}),
}).then(responseJson => {
alert(JSON.stringify(responseJson));
console.log(responseJson);
});
}

You can try interceptor for pass token into header.
Put all requests in one service file name service.js then import Interceptor from '../interceptor';
make one interceptor.js file and write below code in file.
import axios from 'axios';
axios.interceptors.request.use(async (config) => {
if (config.method !== 'OPTIONS') {
config.headers.Authorization = 'Basic cC5qYWltdXJ1Z2FuLm1jYUBnbWFpbC5jb206MTIzNDU2';
}
return config;
}, function (error) {
// Do something with request error
console.log('how are you error: ', error);
return promise.reject(error);
});
axios.interceptors.response.use(
(response) => {
return response
},
async (error) => {
// const originalRequest = error.config
console.log("error in interceptors=============>", error);
if (error.response.status === 500) {
alert(error.response.data.message);
NavigationService.navigate('Login');
} else {
return Promise.reject(error)
}
}
)
export default axios;
When api calls header will pass through by interceptor automatically.

Fetch Api converts all headers into lower-case. We need to do case-insensitive server side parsing.

Related

Axios : authorization header not set on specific request on some iOS devices

I have a vuejs app using axios for http requests.
The authorization header is set via a request interceptor like so :
const api = axios.create({
baseURL: process.env.API_URL,
crossdomain: true,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
api.interceptors.request.use(
function (config) {
if (config.url !== "/register") {
const accessToken = localStorage.getItem('token');
if (accessToken) {
config.headers.Authorization = "Bearer " + accessToken;
}
}
return config;
},
function (error) {
// Do something with request error
return Promise.reject(error);
}
);
All the requests made in the app go through this interceptor. But there is a request for which the authorization header is not set for some ios devices (it works fine on web/android devices and some ios devices). Here is the request :
export function getSessions(context, payload) {
return new Promise((resolve, reject) => {
api.get("/sessions/" + payload.sportId + "/?begin=" + payload.period.from + "&end=" + payload.period.to)
.then(({ data }) => {
resolve(data);
})
.catch((error) => {
reject(error);
});
});
}
I don't understand what could be going wrong. All other requests work fine one the devices for which this one doesn't.
I found the reason of the bug : there was a / before the query (/?begin=). The problem occurred on iOS 14.5, 14.7 and maybe other versions but on any other device there was no error, sometimes a 301 http code was answered but that's it.

Why Axios is not providing response header when app is opening second time?

Here is my API request
const getData= async () => {
const cookie='workid_token=eyJra4rgrtF7SnlSETjIGrFYQy-P2SFmlE6A.Tw_rx0Ut_Kj9zLWRQ9X23w';
const qs = require('qs')
let body = qs.stringify({
gid: '1196'
})
await axios.post(
'https://www.google.com', body,
{
headers: {
'Cookie': cookie,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
).then(response => {
console.log('data', response);
if (response.data.status === '1') {
const PHPSESSID = response.headers['set-cookie'];
var separatedvalue = PHPSESSID[0];
var sessid = separatedvalue.split('; path=/')[0];
}
}).catch(error => {
console.log(error);
});
};
I am implementing Axios API post request in my React Native application. When I run the application first time I am getting set-cookie value in response headers. If I kill the application and I open it second time I am not getting value in set-cookie. Also not receiving response from the API.
Note: I want to receive value from set-cookie all the times.

Vue axios changing Auth Headers with an interceptor

I am new to vue and stuck on this problem for quite some time. I have a login method that retrieves an API token and stores it in localStorage. The login API call is the only call that does not send Auth headers. After the Login every call should add the API token to the header.
When I login the interceptor does not set the new header. It needs a page refresh in the browser to work. Why is that, what am I doing wrong?
In my Login component I have this method:
methods: {
login() {
api.post('auth/login', {
email: this.email,
password: this.password
})
.then(response => {
store.commit('LOGIN');
localStorage.setItem('api_token', response.data.api_token);
});
this.$router.push('reservations')
}
}
Additionally I have this axios base instance and an interceptor:
export const api = axios.create({
baseURL: 'http://backend.local/api/',
// headers: {
// 'Authorization': 'Bearer ' + localStorage.getItem('api_token')
// },
validateStatus: function (status) {
if (status == 401) {
router.push('/login');
} else {
return status;
}
}
});
api.interceptors.request.use((config) => {
config.headers.Authorization = 'Bearer ' + localStorage.getItem('api_token');
return config;
}, (error) => {
return Promise.reject(error);
});

Request Header not being sent as a parameter to API calls

I was trying to make an API call to another domain, which has no-cors enabled.
The API call was made something like this:
let url = `https:sampleApiUrl?params=xxxx`;
console.log("hitting dashboard url")
get(url, token)
.then((resp) => {
console.log("resp", resp)
})
.catch((error) => {
console.log(error)
})
This API call, subsequently calls a 'get' method:
const get = (url, authToken) => {
return baseFetch(url, 'get', false, authToken).then(response => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
const error = new Error(response.statusText);
error.response = response;
throw error;
}
});
}
Now, this get method calls a baseFetch method:
const baseFetch = (url, verb, body, authToken) => {
const request = {
method: verb,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'Access-Control-Allow-Origin': '*',
'credentials': 'include'
},
mode: 'cors'
}
if (authToken){
// adding x-access-token in the request header
request.headers['x-access-token'] = authToken;
}
if (body){
request.body = JSON.stringify(body);
}
return fetch(url, request);
}
Now, when this API call is requested, I can't see the "x-access-token" populated in the browser network call.
No x-access-token in request-headers
Also, I am not sure why I get status code 204 in response.
Calling this API from postman and directly from browser or calling as a curl request, returns the correct response.
Thanks
Looking at the image, you are looking at the headers for pre flight OPTIONS method and not the GET method. The pre flght request is generated by the browser and it never has any custom header. therefore it did not have the x-access-token in its headers.

Cannot get correct error from Axios

I have a doFetch function that handles all my api calls:
const doFetch = function(params){
...
// Make request using Axios. Axios is promise based.
return axios({
method: method,
url: baseUrl + url,
data: queryParams,
timeout: timeout,
headers: {
'Content-Type': contentType,
'Authorization': `bearer ${Auth.getToken()}` // set the authorization HTTP header
},
responseType: responseType
}).then((response) => {
if(typeof params.callback === "function"){
params.callback(response);
}
else {
return response;
}
}).catch((err) => {
if(typeof params.error === "function") {
if (err.response) {
params.error(err.response.data);
}
}
else{
if (err.response) {
return err.response.data;
}
else{
return err;
}
}
});
};
One such api call is returning a custom error like so (express server):
return res.status(400).json("There was an error on the server.");
The function that calls doFetch is saveUser:
saveUser(userObj).then((response) => {
console.log("No Error");
}).catch((error) => {
console.log("Error:", error);
});
The problem is that I am seeing No Error in the terminal, when I should only be expecting the error message to show. Any ideas?
I like to return promise exactly, to be sure that it does/returns what I want.
I don't like to rely on "promise"-s of 3rd parties.
So I would recommend You to wrap it inside of promise and resolve/reject responses/errors manually:
const doFetch = params => {
...
// Make request using Axios. Axios is promise based.
return new Promise((resolve, reject) => {
axios({
method: method,
url: baseUrl + url,
data: queryParams,
timeout: timeout,
headers: {
'Content-Type': contentType,
'Authorization': `Bearer ${Auth.getToken()}` // set the authorization HTTP header
},
responseType: responseType
})
.then((response) => {
console.info('doFetch:', response); // for debug purposes
if(typeof params.callback === "function"){
params.callback(response);
}
resolve(response);
})
.catch((err) => {
console.error('doFetch:', err); // for debug purposes
const error = (err.response) ? err.response.data : err;
if(typeof params.error === "function") {
params.error(error);
}
reject(error);
});
};
};