Develop a flexible axios client

I have a basic axios client setup like this:

import axios from "axios";

const httpClient = axios.create({
  baseURL: "https://localhost:7254/test",
});

httpClient.interceptors.request.use(
  (config) => config,
  (error) => Promise.reject(error)
);

httpClient.interceptors.response.use(
  (response) => response,
  (error) => Promise.reject(error)
);

export default httpClient;

In my service, I currently use it as follows:

export const myService = createService(base);

While this setup works fine, I now want to make the client dynamic so that it can accept any controller instead of being static with /test and

"https://localhost:7254/test"

I would like to be able to do something like this in my services:

 export const myService = createService(`{base}/test`);
 

Is there a way I can achieve this? Thank you.

Answer №1

If you currently pass an instance of axios to your createService function and want to update the baseURL within it, you can simply do the following:

function createService(axiosInstance) {
  axiosInstance.defaults.baseURL = 'something/else/here'
}

Find more information in the documentation:


The original poster may be missing some context, but in most cases, updating the baseURL in this manner is appropriate.

Rather than changing the baseURL after the fact, consider setting the proper value from the beginning. For example:

const httpClient = axios.create({
  baseURL: process.env.BASE_URL,
});

createService(httpClient)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to simulate a constructor-created class instance in jest?

Suppose there is a class called Person which creates an instance of another class named Logger. How can we ensure that the method of Logger is being called when an instance of Person is created, as shown in the example below? // Logger.ts export default cl ...

Testing Angular HTTP error handlers: A comprehensive guide

Below, you will find an example of code snippet: this.paymentTypesService.updatePaymentTypesOrder('cashout', newOrder).subscribe(() => { this.notificationsService.success( 'Success!', `Order change saved successfully`, ...

Angular2 - Actively selecting a checkbox in an ngFor loop with a reactive form

There is an object retrieved from a database that consists of a list of names with their corresponding IDs, as well as a flag to indicate whether they are selected or not. Object: let items = [{ ID: 1, Name: 'Item A', Selected: 'Y ...

What is the method for displaying a server-fetched error message in a form field using Ant Design Vue 3?

My current challenge lies in setting error messages retrieved from the Laravel backend and displaying them on each field that has an error. The data structure for the errors is as follows: { 'errors': { 'email' : ['The Email ...

Grouping elements of an array of objects in JavaScript

I've been struggling to categorize elements with similar values in the array for quite some time, but I seem to be stuck Array: list = [ {id: "0", created_at: "foo1", value: "35"}, {id: "1", created_at: "foo1", value: "26"}, {id: "2", cr ...

Creating a custom component results in an extended duration to 'eliminate' its children

1I am currently facing an issue with a time-table component created using vue.js. It contains approximately 200 nested child timeline components, making it quite complex (I wanted to share an image but lacked the reputation to do so). The main problem lie ...

An error occurred in TypeScript when trying to use the useState function with a string type. The ReferenceError indicates that

import React, { FunctionComponent, useState, useEffect } from 'react' const SearchBar: FunctionComponent = () => { const [searchValue, setSearchValue] = useState<string>('') const [isSuggestionOpen, setIsSuggestionO ...

Upgrade Challenge from Angular 7 to Angular 9

I am currently in the process of upgrading my application from version 7 to version 9. However, I have encountered an issue with the new IVY compiler in Angular 9 not being compatible with the library angular-webstorage-service, resulting in the following ...

What is the process for combining multiple Vue components into a cohesive npm package?

My project manager at work tasked me with creating a single npm package for all the global components in our Vue project. This package should be easily importable and usable by everyone working on the project, similar to how Vuetify is imported from the no ...

Creating a customized design for a q-popup-edit

As I navigate through using Quasar in Vue, I stumbled upon a q-popup-edit that allows me to gather input from the user. Despite my attempts at researching via Google and reading documentation, I have hit a roadblock when it comes to customizing the style o ...

Retrieve information prior to CanActivation being invoked

As I develop a web application utilizing REST to retrieve data (using Spring Boot), the server employs cookies for authenticating logged-in users. Upon user signing in, I store their information in the AuthenticationHolderService service (located in root ...

Issue with splitting an array and eliminating commas - angular/ReactJS

Console Error: Unhandled error during execution of mounted hook Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'split') It seems to work up until it comes across a group that has no data for continent. This looks ...

Support for dark mode in Svelte with Typescript and TailwindCSS is now available

I'm currently working on a Svelte3 project and I'm struggling to enable DarkMode support with TailwindCSS. According to the documentation, it should be working locally? The project is pretty standard at the moment, with Tailwind, Typescript, and ...

In Vue, it is not possible to modify the value of one variable while simultaneously altering another variable

How can I instantly change the value of 'countcolor' when inputting a value for 'count'? Do I need to introduce a component for this or is there a binding issue? What should be done? <div id="app-13"> Enter ...

Dealing with 'TypeError X is Not a Function' Error in Angular (TypeScript): Occurrences in Certain Scenarios and Absence in Others

Recently, I came across an odd issue in Angular 14 where a type error kept popping up. Although I managed to refactor the code and find a workaround, I'm quite intrigued as to why this issue is happening so that I can prevent it from occurring again i ...

Using socket.io-client in Angular 4: A Step-by-Step Guide

I am attempting to establish a connection between my server side, which is PHP Laravel with Echo WebSocket, and Angular 4. I have attempted to use both ng2-socket-io via npm and laravel-echo via npm, but unfortunately neither were successful. If anyone h ...

Storing Data Property Value from an Item in Rendered List Using Vue: A Quick Guide

I'm currently working on implementing a follow button for list items in Vue. My approach involves extracting the value of a specific property from a list item and storing it in the data object. Then, I plan to utilize this value within a method to app ...

TypeScript does not raise errors for ANY variables that are initialized later

In my code, there is a function that accepts only numeric variables. function add(n1: number) { return n1 + n1; } However, I mistakenly initialized a variable with type "any" and assigned it a string value of '5'. let number1; number1 = &apo ...

Vue.js is unable to render the template using Object

During this demonstration at https://jsfiddle.net/ccforward/fa35a2cc/, I encountered an issue where the template could not render and the data in resultWrong remained empty with a value of {} At https://jsfiddle.net/ccforward/zoo6xzc ...

Guide to inserting a YouTube video or any iframe using vue-dompurify-html

Recently, I completed a blogging project in Nuxt where I utilized the quill text editor for managing content in the description field of my database. However, upon trying to display the blog post's description from the database using v-html, I encoun ...