Home > other >  Type '{ 'x-access-token': any; } | { 'x-access-token'?: undefined; }'
Type '{ 'x-access-token': any; } | { 'x-access-token'?: undefined; }'

Time:12-16

I have an autHeader and I want to add it to the "Service", but this error appeared:

Type '{ 'x-access-token': any; } | { 'x-access-token'?: undefined; }' is not assignable to 
type 'AxiosRequestHeaders | undefined'.
Type '{ 'x-access-token'?: undefined; }' is not assignable to type 'AxiosRequestHeaders'.
Property ''x-access-token'' is incompatible with index signature.
Type 'undefined' is not assignable to type 'string'.

How can I solve the problem?

And what's the best place to add "authheader" to it?

todo.service.ts:

import authHeader from './auth-header';

// create columns
async function createList(title: string) {
  const response = await axios.post(
    'http://ec2-18-132-52-86.eu-west-2.compute.amazonaws.com/api/v1/todo-list',
    { title: title },
    { headers: authHeader() }
  );
  return response;
}

auth-header.ts:

const authHeader = () => {
  const userInfo = localStorage.getItem('userInfo');
  let user = null;
  if (userInfo) {
    // convert strng to Object
    user = JSON.parse(userInfo);
  }

  if (user && user.accessToken) {
    // return { Authorization: 'Bearer'   user.accessToken }
    return { 'x-access-token': user.accessToken };
  } else {
    return {};
  }
};

export default authHeader;

CodePudding user response:

Here's a type-safe refactor of your two functions. I left some comments to explain:

TS Playground

import {
  default as axios,
  AxiosRequestConfig,
  AxiosRequestHeaders,
} from 'axios';

type UserInfo = {
  accessToken: string;
};

export function getAuthHeaders (): AxiosRequestHeaders {
  // Set this to whatever the minimum token length should be (if you know)
  // Otherwise, you can leave at 1 for "not an empty string"
  const minTokenLength = 1;

  try {
    const userInfo = localStorage.getItem('userInfo');
    // Abort if not string
    if (typeof userInfo !== 'string') throw new Error('User info not found');

    // Destructure token
    const {accessToken} = JSON.parse(userInfo) as UserInfo;

    // Abort if token is not string and min length
    if (!(typeof accessToken === 'string' && accessToken.length >= minTokenLength)) {
      throw new Error('Invalid user access token');
    }

    // I left this here because it seems like you weren't sure about which format you need:
    // return {Authorization: `Bearer ${accessToken}`};

    // Return headers object
    return {'x-access-token': accessToken};
  }
  catch {
    // Catch any errors and return an empty headers object
    return {};
  }
}

async function createList (title: string) {
  const data = {title};
  const url = 'http://ec2-18-132-52-86.eu-west-2.compute.amazonaws.com/api/v1/todo-list';
  const requestConfig: AxiosRequestConfig = {headers: getAuthHeaders()};
  return axios.post(url, data, requestConfig);
}

const axiosResopnse = await createList('myList');

CodePudding user response:

First Create an Axios object instance.

At todo.service.ts

let instance = axios.create()

After the instance has been created set the headers for post requests

At todo.service.ts

const userInfo = localStorage.getItem('userInfo');
  let user = null;
  if (userInfo) {
    // convert strng to Object
    user = JSON.parse(userInfo);
  }
//This will set the default authorization field for all post requests header
instance.defaults.headers.post['Authorization'] = 'Bearer'   user.accessToken

Now inside your function use the Axios instance to make a post request

async function createList(title: string) {
  const response = await instance.post(
    'http://ec2-18-132-52-86.eu-west-2.compute.amazonaws.com/api/v1/todo-list',
    { title: title }
  );
  return response;
}
  • Related