0

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);

  });
}
3
  • 2
    Show me the code you tried. Commented Sep 23, 2019 at 16:57
  • Please post the code you tried using both the Fetch API as well as XMLHttpRequest Commented Sep 23, 2019 at 22:31
  • I have add my code. Please have a look. Commented Sep 24, 2019 at 4:43

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

could you please explain

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.