How to pass Header JWT Token with Axios & React?

前端 未结 4 864
你的背包
你的背包 2021-01-31 11:57

I make web application with React, Express, MongoDB.

And, I want to pass jwt token with header.

But, I pass it, get 401 error (Unauthorized).

In login ac

4条回答
  •  粉色の甜心
    2021-01-31 12:23

    how-to-pass-header-jwt-token-with-axios-react ???


    This is example for create axios instance with API Base URL and JWT_TOKEN globally and access it for different API calls

    step 1 : create static instance for axios

    static axiosInstance =  axios.create({
        baseURL: "BASE_API_URL",
        timeout: 5000,
        headers: {
          'Authorization': "JWT_TOKEN",
          'Content-Type': 'application/json'
        }
      }); 
    

    this is the second setep access axiosInstance already create and use it with dynamic REST API calls

    step 2 : access static instance and bind API_URL to base URL

    export const x = (data) => dispatch => {
        axiosInstance.post('API_URL',
            {
                PLAYLOAD
            })
            .then(function (response) {
    
            })
            .catch(function (error) {
    
            });
    }
    

    API URL = BASE_API_URL + API_URL and single JWT_TOKEN for all and this very clean , clear and working.

提交回复
热议问题