Hyeongwoo Jeon
Hyeongwoo Jeon

Reputation: 39

REACT + Typescript, making API with Axios. headers makes type error

I'm so Newbie in Programming.

I'm using Django as backend, React+Typescript as frontend.

I'm using Axios to make JWT login function. but stuck in the middle.

Because headers/Authorization makes type error.

enter image description here

as above Authorization does not work. enter image description here

showing this error.

Can anyone help me out of this situation?

Upvotes: 0

Views: 1081

Answers (2)

Shahzad Khan
Shahzad Khan

Reputation: 530

const axiosbase = axios.create({
  baseURL: 'Your Base URL',
  timeout: 5000,
    transformRequest: [(data, headers) => {  
        return data;
      }]
});

//default headers
var token = 'Your JWT';
axiosbase.defaults.headers["Authorization"] = 'Bearer ' + token;
axiosbase.defaults.headers["Accept"] = 'application/json, text/plain, */*';
axiosbase.defaults.headers["Content-Type"] = 'application/json';

// Add a request interceptor
axiosbase.interceptors.request.use((config) => {   
    return config;
  }, (error) => {
    // Do something with request error
    console.log('Error occured while request');
    return Promise.reject(error);
  });

// Add a response interceptor
axiosbase.interceptors.response.use(
  (response) => {
    // Do something with response data
    //console.log('Response was received');
    return response;
  },
);

export default axiosbase;

Upvotes: 0

Disco
Disco

Reputation: 1634

Try to remove the null in your condition. Replace it with either undefined or a empty string ""

Authorization: localStorage.getItem("access_token") ? "JWT" + localStorage.getItem("access_token") : ""

Upvotes: 2

Related Questions