Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinatra + Angularjs Routing

I have an Angularjs app running on Sinatra.

My Angular routes are working if I click on a link within the app, however if I visit the url directly I get a 404 from Sinatra.

Is there a way to pass the routing from Sinatra to Angular?

Currently all Sinatra is doing is loading the index.html

get '/' do
  File.read "#{Dir.pwd}/app/index.html"
end
like image 388
vladiim Avatar asked Mar 05 '26 12:03

vladiim


2 Answers

Thanks to @Ryan I ended up implementing a working solution.

get '/*' do
  File.read "#{Dir.pwd}/app/index.html"
end
like image 98
vladiim Avatar answered Mar 08 '26 10:03

vladiim


One way you could do this would be to set up a catch-all route with Sinatra to pass requests on to your angular app. I'm not very familiar with the sinatra framework, but for flask this is how you do it:

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def index(path):
    return make_response(open('templates/index.html').read())

Just find the equivalent for Sinatra and you'll be good to go.


EDIT: I realized it is probably not the best idea to set up a catch-all route, especially if you are building a website (and using "$locationProvider.html5Mode(true)" vs. building a single-page webapp), for which returning proper 404's is important for search engine indexing, etc.

I would instead register a flask route for every route in your Angular app. In flask, this is how you do it.

@app.route('/')
@app.route('/about')
def index(path):
    return make_response(open('templates/index.html').read())

In sinatra, I'd suppose it would be something like this:

get '/' do
get '/about' do
    File.read "#{Dir.pwd}/app/index.html"
end

EDIT: It really depends what you're going for. Some sites want their entire site to be an angular app (and don't prioritize SEO, proper 404's, etc.) and others want a particular section to be reserved for their angular app. You might see "/app/OTHER_STUFF", for example. In that case, a catch all would work well.

like image 20
Ryan Shea Avatar answered Mar 08 '26 11:03

Ryan Shea