2

My backend is python + flask, frontend is vuejs.

My routes:

in flask, I have only 2 routes:

  • 404
  • /

But in vuejs's routes:

  • /
  • /search
  • /about
  • /contact

the problem I met is like:

When I visit myname.com/search

Visit in local dev

0.0.0.0:8001/search

It is fine

Visit in server:

myname.com/search

It give me 404, because this is not a route in flask

I think I know why this happened, but I have no idea how to fix it, waiting for some help.

tim
  • 1,454
  • 1
  • 25
  • 45

2 Answers2

4

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 here
def index(page):
    return app.send_static_file('index.html')
Jeffery Li
  • 565
  • 1
  • 4
  • 13
3

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

Community
  • 1
  • 1
Nathan Wailes
  • 9,872
  • 7
  • 57
  • 95
  • But if I want user to access certain content that is not static directly with a url how do I tell Vue to re-render or take the steps to render the asked view? – KasparTr May 31 '18 at 16:58