Mutre
Mutre

Reputation: 155

Wrong link to assets with Vue Router when there is a / in the URL

In my Vue Router configuration I have this route:

{
  path: "/edit/:id",
  name: "editRegistration",
  component: EditRegistration,
},

When I go to e.g. http://localhost:8080/edit/1 it works, except for one thing: I have an image tag with the source src="img/logo.png" (not in the EditRegistration component but the one that includes it), so my browser tries to find it in the non-existing directory /edit and the image is not displayed.

That happens only when I go directly to the aforementioned URL, not if I first go to http://localhost:8080/ and then go to the page by clicking on router links.

I am confused because I worked on other projects with Vue Router and I don't remember having this issue. My vue.config.js contains the following config:

module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? '/2023' : '/',
}

Instead of '/' I had previously an empty string and when I went to ´/edit/1` my browser couldn't even find the JS files.

I am using the development server (npm run serve), Vue 3 and Vue Router 4.

Any ideas? I guess I could add the absolute path before every image URL but it feels like there should be a simpler solution.

Upvotes: 1

Views: 263

Answers (1)

Mutre
Mutre

Reputation: 155

I found a simple workaround: adding <base href="<%= BASE_URL %>"> in the <head> section of public/index.html.

Upvotes: 2

Related Questions