Operatorius
Operatorius

Reputation: 328

VueJs 2: Unable to render view when using history mode and route params

I am trying to set up SPA routes using history mode as follows:

{
  mode: 'history',
  routes: [
    {
      path: '/',
      component: Home
    },
    {
      path: '/articles',
      component: ArticleList,
      children: [
        {
          path: ':title',
          component: ArticleView
        }
      ]
    }
  ]
}

As I am using the history mode routing on vue and on express application I've set up "express-history-api-fallback" as the last middleware in the pipeline:

const app = express();
const root = path.join(__dirname, '../client/dist');
app.use(express.static(root));
/* other middlewares */
app.use(fallback('index.html', {root: root}));

At the moment of a page reload, everything works fine. I.e. loading a url http://application/articles, opens correctly the view, BUT when I try to access the view that takes in a parameter, no matter what, the view does not get loaded and two requests are made to the express.

I.E. a request to http://application/articles/test will resolve into two requests. One to http://application/articles/test and another one to http://application/articles/app.[calculated-hash].js As far as I understand, the first request fetches the index.html the other request fetches the bundled js script.

Also, on the express app, all routes to api start with 'api' prefix.

Question: What is wrong with my setup/code using history mode and route params because no routes with parameters are loaded when trying to access them when entering url manually or hitting refresh?

Update: Using connect-history-api-fallback produces the same results

Upvotes: 1

Views: 1570

Answers (1)

Operatorius
Operatorius

Reputation: 328

The problem was with the script tag the webpack injects into the index.html

<script type="text/javascript" src="app.06503cbc260646a996d9.js"></script>

The src attribute value was missing a '/' prefix thus the resolution of files failed.

So to make it work, I've linked the src file like this:

<script type="text/javascript" src="/app.06503cbc260646a996d9.js"></script>

As I am using the webpack to bundle js files, on the webpack config I've added output.publicPath '/'

More info: connect-history-api-fallback bugtracker

Upvotes: 2

Related Questions