vue.jsvuejs3

Vuejs 3 - Calls to backend inserting part of route when multiple subdirectories are in URL


New to vuejs, completely stumped by this. Here is my config:

export 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))
    },
  },
})

Here are my routes so far:

routes: [
    {
      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, with home, recipe, add, and edit all make backend calls on onMounted. Home and recipe are making the proper calls, recipe for example:

state.recipes = (await axios.get('api/recipes')).data;

(https://i.sstatic.net/AsFdzc8J.png) (http://localhost:7000/api/recipes)

But add and edit are somehow getting part of the route path inserted, add for example:

state.allCategories = (await axios.get('api/categories')).data;

(https://i.sstatic.net/H3PrHdjO.png) (http://localhost:7000/recipes/api/categories)

I have no idea why the 'recipes' part is in there on this call. If I change the path in the route to one subdirectory, like 'recipe-add', then the URL is correct and my backend returns data. Any help would be greatly appreciated.


Solution

  • 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.