1

I have an application with an AngularJS frontend and a Flask backend.

I have the following routes in Flask to send all requests to the index.html file (as well as some routes for API routes):

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/api/colours')
def colours():
    ...

@app.route('/<path:page>')
def fallback(page):
    return redirect(url_for('home'))

I'm then using the Angular StateProvider for the client-side routing:

$stateProvider
    .state('home', {
        url: '/',
        templateUrl: 'static/templates/home.html'
    })
    .state('contact', {
        url: '/contact', 
        templateUrl: 'static/templates/contact.html'
    });

This works great if I start at the root of my website and click a link to take me to the contact page. However, if I want to go to straight to the contact page by typing in mysite.com/contact it redirects the homepage. Which is expected.

How can I allow it go to the client side route if it's available, else redirect to home page?

3
  • What do you mean by "Which is expected"? it has to show you contact.html right? Commented Aug 22, 2017 at 13:56
  • I meant it's expected because the server-side routing rule says redirect home, as it doesn't know about /contact. Commented Aug 22, 2017 at 14:06
  • I see. Right answer is already given in that case :) Commented Aug 22, 2017 at 15:09

1 Answer 1

3

From server side if you encounter home or unknown route (404) you should return index.html since you don't know if client side can handle this route. After index.html is loaded client side routing should take over and decide whether to redirect to Not found or handle this route in some other way.

@app.route('/<path:page>')
def fallback(page):
    return render_template('index.html')
Sign up to request clarification or add additional context in comments.

3 Comments

That works. Rendering index.html is correct instead of routing to home and rendering index.html from there. Thanks @Žilvinas!
Also for Angular > 2!
Yes, this works for Angular 11+. Now we need to make 404 with Angular. let's Angular do the job!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.