0

I´m using Flask with a frontend developed in vue that has vue router inside, so when you are going to localhost:80/, Flask send to you the html bundle produced by npm run build command. All the api calls, are in the api/ route localhost:80/api/YourCall

The trick is that the frontend has it owns router system, for example localhost:80/getAll with returns the webpage generated by vue, and that webpage calls localhost:80/api/getAll which retrieves the data and send it back.

I achieve this functionality with the following code:

@app.route('/',defaults={'path': ''})
@app.route('/<path:path>')
def index(path):
    if path != "" and os.path.exists(app.static_folder + '/' + path):
        return send_from_directory(app.static_folder, path)
    else:
        return send_from_directory(app.static_folder, 'index.html')

Now, I´m trying to migrate to FastApi, and I found that localhost:80/getAll returns a 404, because the route is handle by FastApi before the webpage, so obviously the result is 404. I tried to solve this following the answers here and here with no results. Also I tried the code from this answer

from fastapi.staticfiles import StaticFiles

class SPAStaticFiles(StaticFiles):
async def get_response(self, path: str, scope):
   response = await super().get_response(path, scope)
   if response.status_code == 404:
       response = await super().get_response('.', scope)
   return response

app.mount('/my-spa/', SPAStaticFiles(directory='folder', html=True), name='whatever')

Which is similar to my previous way of working, without positive results. Is what I´m trying to do even possible?

F.Stan
  • 553
  • 1
  • 10
  • 23
  • 1
    Does [this](https://stackoverflow.com/a/73113792/17865804) answer your question? – Chris Jul 12 '23 at 15:52
  • Yes, it didn't work following the code snip, but it gave me the technical background, so now I have a workaround, is not as simple as it is with Flask but now is working, if I don't receive any other answer, I'll answer it with the workaround. Thank you Chris – F.Stan Jul 13 '23 at 06:35
  • You might find [this](https://stackoverflow.com/a/76057623/17865804), [this](https://stackoverflow.com/a/72815364/17865804), as well as [this](https://stackoverflow.com/a/73295133/17865804) and [this](https://stackoverflow.com/a/74556972/17865804) helpful as well. – Chris Jul 13 '23 at 09:19

0 Answers0