Search code examples
javascriptnode.jsaxiosbackendtrello

Not able to make api call using axios instance


export class TrelloService {
    public instance: AxiosInstance;
    constructor(token: string) {
        this.instance = axios.create({
            baseURL: `https://api.trello.com/1?key=${process.env.TRELLO_API_KEY}&token=${token}`,
        });
    }

    public async getUserDetails(email: string): Promise<any> {
        const userDetails = await this.instance.get(`/members/${email}`);
        return userDetails;
    }
    
    public static async getUserDetails2(
        email: string,
        token: string,
        throwError = false,
    ): Promise<any> {
        let userDetails: any = null;

        const userDetails = await axios.get(`https://api.trello.com/1/members/${email}key=${process.env.TRELLO_API_KEY}&token=${token}`)
        return userDetails;
    }
}

If i am invoking getUserDetails by creating an object of class TrelloService, its not working. Trello it throwing me an error with status code 404. But if I directly invoke getUserDetails2 method it is working fine. This is the object creation part

    const trelloService = new TrelloService(accessToken);
    const temp = await trelloService.getUserDetails(email);

I tried manipulating axios instance but it didn't work out for me. Is it because url is getting attach at the end, even after query variable?


Solution

  • I think the issue is because axios merge the strings together

    You have to use the params option

    Change this line

    this.instance = axios.create({
      baseURL: `https://api.trello.com/1?key=${process.env.TRELLO_API_KEY}&token=${token}`,
    });
    

    to

    this.instance = axios.create({
      baseURL: `https://api.trello.com/1`,
      params: {
        key: process.env.TRELLO_API_KEY,
        token: token,
      }
    });