Vue.js front-end routing conflicts with back-end flask routing Vue.js front-end routing conflicts with back-end flask routing flask flask

Vue.js front-end routing conflicts with back-end flask routing


I've encountered the same issue and solved it with Flask catch-all rules. Flask will catch the url /books and then pass it to Vue application.

@app.route('/', defaults={'path': ''})@app.route('/<path:path>')               # url /books will fail into heredef index(page):    return app.send_static_file('index.html')


As mentioned in the documentation for vue-router:

When using history mode, the URL will look "normal," e.g. http://oursite.com/user/id. Beautiful!

Here comes a problem, though: Since our app is a single page client side app, without a proper server configuration, the users will get a 404 error if they access http://oursite.com/user/id directly in their browser. Now that's ugly.

Not to worry: To fix the issue, all you need to do is add a simple catch-all fallback route to your server. If the URL doesn't match any static assets, it should serve the same index.html page that your app lives in. Beautiful, again!

So it appears that you'll either need to configure your server to handle such requests correctly, or it won't be possible to have your URLs look "normal" (without the hash) and still be able to link directly to that page.


In a somewhat-related example, you'll notice that if you use Gmail (a single-page-application, like what you're building), the link to the settings page is not a "normal" link, but instead lists the particular page being visited after the hash (#): https://mail.google.com/mail/u/0/#settings/general.


This GitHub project, which is linked to from the vue-router documentation, gives a fairly good overview of what your Flask server may need to do to handle incoming requests that are using "normal" URLs:

  1. Intercept incoming requests.
  2. Check the URL to make sure it isn't requesting a static file.
  3. Redirect / rewrite the requested URL so that it will be routed to the correct endpoint.

Related SO question: Vue Router return 404 when revisit to the url