Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
How to update this axios service for being able conditionally decide which API URL to use?

I have the following axis service:

   const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'Authorization': 'Bearer '+token}
});

I need conditionally pass isAdmin from outside for being able to switch the API URL here. How can be it achieved.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

We could pass in the value into the constructor, and pass it to the initInstance method, then return the URL contingent on the value of isAdmin.

class AxiosService {
    // ...

  constructor(isAdmin = false) {
    this.initInstance(isAdmin);
  }

  initInstance(isAdmin) {
    this.axiosInstance = axios.create({
      baseURL: isAdmin ? '/api/admin/v1' : '/api/v1',
      timeout: 5000
    });
        
        // ...
  }
    
    // ...
}

To use these, we'd now go...

const axiosService = new AxiosService(true); // admin url will be used
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use multiple instances for each baseURL and call the instance by isAdmin condition. However, you can config the defaults that will be applied to every request.

import axios from "axios";
    
/* default config for each request */
axios.defaults.headers['Authorization'] = 'Bearer ' + token;
axios.defaults.timeout = 1000;

const adminAxios = axios.create({
    baseURL: 'https://some-domain.com/api/'
});
    
const nonAdminAxios = axios.create({
    baseURL: 'https://other-some-domain.com/api/'
});
    
    
const getInstance = (isAdmin) => isAdmin ? adminAxios : nonAdminAxios;

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda