NodeJS 无法使用axios示例进行API调用

bmp9r5qi  于 2023-04-05  发布在  Node.js
关注(0)|答案(2)|浏览(149)
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;
    }
}

如果我通过创建类TrelloService的对象来调用getUserDetails,它不工作。Trello它会向我抛出状态代码为404的错误。但是如果我直接调用getUserDetails2方法,它工作正常。这是对象创建部分

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

我试着操作axios示例,但没有成功。是不是因为url在最后被附加,甚至在查询变量之后?

q8l4jmvw

q8l4jmvw1#

我认为问题是因为axios把字符串合并在一起
必须使用params选项
更改此行

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

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

vqlkdk9b2#

很遗憾,您正在尝试获取无效的URL:

# invalid:
https://api.trello.com/1?key=key&token=token/members/john@doe.io

# valid:
https://api.trello.com/1/members/john@doe.io?key=key&token=token

尝试在每个请求中添加参数:

export class TrelloService {
  public instance: AxiosInstance;
  public baseParams: { key: string; token: string };

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

  public async getUserDetails(email: string): Promise<any> {
    const userDetails = await this.instance.get(`/members/${email}`, {
      params: { otherParam: "1", ...this.baseParams },
    });
    return userDetails;
  }
}

您还可以使用interceptor向每个请求添加参数

相关问题