HTTP with Axios

suggest change

Configure

For HTTP requests you can also use Axios.

Create a file such as axios.js. serverURL is your API origin.

import * as axios from 'axios';

var instance = axios.create();
instance.defaults.baseURL = serverURL;
instance.defaults.timeout = 20000;
// ...
// and other options

export { instance as default };

and then use it in any file you want.

Requests

To avoid one catch-all module for every backend service, create a separate file of methods for each service:

import axios from '../axios';
import { 
    errorHandling
} from '../common';

const UserService = {
        getCallToAction() {
        return axios.get('api/user/dosomething').then(response => response.data)
            .catch(errorHandling);
    },
}
export default UserService;

Testing

There is a special lib for testing axios: axios-mock-adapter.

With this library you can make Axios return any response you need in a test, including errors. Keep the mock in the test only. If you leave it on the app instance, every request returns 500.

import MockAdapter from 'axios-mock-adapter';

var mock = new MockAdapter(instance);
mock.onAny().reply(500);

Redux Store

Sometimes you need to send an authorization token that you store in Redux.

In that case, add a file such as interceptors.js:

export function getAuthToken(storeContainer) {
    return config => {
        let store = storeContainer.getState();
        config.headers['Authorization'] = store.user.accessToken;
        return config;
    };
}

In the root component's constructor:

axios.interceptors.request.use(getAuthToken(this.state.store));

Every later request then includes that authorization token.

Axios is a small, configurable HTTP client for React Native apps.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents