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?