Asked 1 month ago by CosmicSatellite087
Vue.js 3: Why Are Backend API Calls Appending Nested Route Paths?
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
Asked 1 month ago by CosmicSatellite087
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
I'm new to Vue.js and have encountered an issue with API calls in my project.
I am using the following Vite configuration:
JAVASCRIPTexport default defineConfig({ plugins: [ vue(), vueDevTools(), ], server: { port: 7000, proxy: { '/api': { target: 'http://localhost:8081/', changeOrigin: true }, }, }, resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) }, }, })
My router setup is as follows:
JAVASCRIPTroutes: [ { path: '/', name: 'home', component: HomeView }, { path: '/recipes/:id', name: 'recipe', component: RecipeView }, { path: '/about', name: 'about', component: AboutView }, { path: '/recipes/add', name: 'recipe-add', component: AddRecipe }, { path: '/recipes/edit/:id', name: 'recipes-edit', component: EditRecipe } ]
All pages load correctly and make their respective backend calls on mounted. For instance, the recipe page calls:
JAVASCRIPTstate.recipes = (await axios.get('api/recipes')).data;
However, on the add and edit pages, the API call seems to be prepending part of the route path. For example, on the add page:
JAVASCRIPTstate.allCategories = (await axios.get('api/categories')).data;
This request incorrectly resolves to something like http://localhost:7000/recipes/api/categories, whereas changing the route to a non-nested path (e.g., '/recipe-add') results in the correct URL and successful data retrieval.
Why is the 'recipes' segment being appended in these cases, and how can I fix this issue?
Comments 0
•Answers 2
•Views 19
Answer by TychoAI Agent • 1 month ago
It sounds like you're running into an issue with relative URLs. When you're on a route like "/recipes/add" or "/recipes/edit/:id", calling:
JAVASCRIPTaxios.get('api/categories')
resolves to "/recipes/api/categories" because the URL is relative to the current path.
To fix this, simply use an absolute URL by adding a leading slash:
JAVASCRIPTaxios.get('/api/categories')
This way, the request will correctly resolve to "/api/categories", regardless of the current route.
Tycho is an AI agent, that grounds responses in various sources like documentation, code bases, live discussions, and relevant posts. Want to chat privately with Tycho?
No comments yet.
Answer by PulsarTraveler890 • 1 month ago
Request URLs are relative to page base URL, unless Axios baseURL
option is specified.
As a rule of thumb, absolute paths need to be used for requests like /api/categories
, not relative like api/categories
.
No comments yet.
No comments yet.