marcushaddon
marcushaddon

Reputation: 23

Base tag breaks script links in Angular HTML5 mode

Problem

After setting a base tag to run Angular 1.x in HTML5 mode, the browser (Chrome) makes requests to the wrong path for scripts when accessing the app by navigating directly to localhost:3000/resource/id.

Details

I have an Angular 1 app that I have recently set to run in HTML5 mode, like so:

    $locationProvider.html5Mode(true);

I have included a base tag in the head of index.html like so:

<base href="/">

I have set up my express routes so that a request for (for example) http://localhost:3000/album/38ad87f will return index.html, like so:

    .use('/', express.static(__dirname + '/crate-frontend/app'))

// Playlist endpoints
.use('/api/playlists', playlistRoutes)

// Album endpoints
.use('/api/album', albumRoutes)

// Artist endpoints
.use('/api/artist', artistRoutes)

// Track endpoints
.use('/api/tracks', trackRoutes)

// User endpoints
.use('/api/user', userRoutes)

// Discogs proxy endpoints
.use('/api/discogs', discogsRoutes)

// Youtube proxy endpoints
.use('/api/youtube', youtubeRoutes)

// Search endpoints
.use('/api/search', searchRoutes)

// For serving up crate-frontend/app/index.html
.all('/*', function(request, response){
    response.sendFile(__dirname + '/crate-frontend/app/index.html' );
})

Now, when I go to the home page, and navigate around, everything works fine. BUT if I refresh the page that is not the root OR a copy/paste a URL like http://localhost:3000/album/38ad87f into a new window, it breaks. I can see that it receives index.html, but then when the browser requests each of the linked scripts, for example:

<script src="app.js"></script>

it actually makes a request to http://localhost:3000/album/app.js, which returns index.html.

Can someone tell me what I've missed / am doing wrong?

Upvotes: 2

Views: 172

Answers (1)

lin
lin

Reputation: 18392

Try to include your ressources with an absolute path and you will be fine for all time.

<script src="/app.js"></script>

Upvotes: 0

Related Questions