'React + axios + redux interceptors

I have an React + redux + axios app, white jwt authentication. So, i need to intercept every request to server and set header with token. The question is where I have to set this headers, or implement interceptors. (also, i need redux store in scope, to get tokens from store). My idea - implement it in the Index component. Is it right way?



Solution 1:[1]

I suggest you to set the header axios.defaults.headers.common.authorization. Take a look here Global axios defaults. If you need a working example, this public repo can help you out.

Solution 2:[2]

Why do you have to manually set the header. Can't you just store the JWT in a cookie and then the browser will forward it automatically for you. Just make sure you pass credentials: 'include' in your HTTP options.

Solution 3:[3]

create a redux-middleware to do these things.

Apart from acting like interceptor to add header token, you also do request/response transformation.

Also,you can mention the next action to which you want to dispatch the result if you don't want to return the promise and result.

Middleware gives you a chance to get the store state and also fetch & dispatch other action

const apiInterceptor = store => next => action => {

      if(action.type !== 'ajax') return next(action)

      const state = store.getState();

      state.token // get token here

      //add this api check part in some other module.
      if(action.api=='UPDATE_CLIENT') 
        {
          method = 'post';
          url  = 'some url';
        }
      else
      {
        method = 'get';
        url  = 'other url';
      }


      fetch(url, {
        method: method,
        headers : 'add token here',
        body: JSON.stringify(action.body())
      })
      .then(response => response.json())
      .then(json => json)//either return result
      //OR dispatch the result
       .then(json => {

         dispatch({type:action.next_action,payload : json})        
       })
    }

Integrate the middleware with store.

import customMiddleware from './customMiddleware'
const store = createStore(
  reducer,
  applyMiddleware(customMiddleware)
)

Solution 4:[4]

I offer you to refer redux-thunk.

You must create api-wrapper-helper to inject to redux-thunk as extra argument, then access to api-wrapper-helper from redux actions.

api-wrapper-helper is a function that get url and method as argument and send request to api-server then return result. (you can set headers in this file)

For example you can see ApiClient.js of react-redux-universal-hot-example boilerplate.

Solution 5:[5]

This is an old post but its getting a few views, so something like this would work nicely and is easily testable.

apiclient.js

import axios from 'axios';

import { setRequestHeadersInterceptor } from './interceptors';

const apiClient = axios.create(
{
  baseUrl: 'https://my.api.com',
  timeout: 3000
});

apiClient.interceptors.request.use(setRequestHeadersInterceptor);

export default apiClient;

interceptors.js

export const setRequestHeadersInterceptor = config =>
{
   // have each interceptor do one thing - Single Responsibility Principle
};

you should store your auth details in a httpOnly secure cookie, the transmission to/from the server will be automatic then

Solution 6:[6]

//  Interceptor
axios.interceptors.response.use(function (response) {
// success case here
    return response
}, function (error) {

// Global Error Handling here
//    showErrorToaster(error['message']);
    return Promise.reject(error.response.data)
})

Solution 7:[7]

Instead of what you have done, you can go through a simple and general way like this:

a = input().split()

for i in range(len(a)):
    for j in range(len(a)):
        if j>=i:
            print(*a[i:j+1])

Output:

1
1 2
1 2 3
2
2 3
3

Solution 8:[8]

Try the following:

t = int(input())
for z in range(t):
    n = int(input()) 
    a = []
    for y in range(n):
        x = int(input())
        a.append(x) 

    for i in range(n):
        for j in range(i,n+1):
            for k in range(i,j):
                print(a[k], end=" ")
            print()

Solution 9:[9]

(try this) You can get and print all subsets of an array by the next:

In array A at every step, we have two choices for each element either we can ignore the element or we can include the element in our subset.

function


def subsetsUtil(A, subset, index):
    print(*subset)
    for i in range(index, len(A)): 
        
        # include the A[i] in subset. 
        subset.append(A[i])
        
        # move onto the next element. 
        subsetsUtil(A, subset, i + 1) 
        
        # exclude the A[i] from subset and 
        # triggers backtracking.
        subset.pop(-1) 
    return

below function returns the subsets of vector A.

def subsets(A):
    global res
    subset = []
    
    # keeps track of current element in vector A 
    index = 0
    subsetsUtil(A, subset, index) 

Implement the array and call the function

array = [1, 2, 3]
subsets(array) 

-> res will store all subsets.

Time complexity

O(2 ^ (number of elements inside array))

--> because at every step we have two choices either include or ignore.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rafael Sousa
Solution 2 Adam
Solution 3
Solution 4
Solution 5
Solution 6 Shashwat Gupta
Solution 7 Mohammad Khoshbin
Solution 8 Sanskar Agarwal
Solution 9