플라스크 및 반응 경로
React로 Flask 앱을 만들고 있는데 라우팅에 문제가 생겼습니다.
백엔드는 API가 되기 때문에 다음과 같은 루트가 있습니다.
@app.route('/api/v1/do-something/', methods=["GET"])
def do_something():
return something()
반응으로 이어지는 주요 경로:
@app.route('/')
def index():
return render_template('index.html')
리액트 앱에서 리액트 라우터를 사용하고 있는데, 모든 것이 정상적으로 동작하고 리액트 라우터를 사용하면/something렌더링된 뷰는 표시되지만 페이지를 새로 고치면/something그러면 플라스크 앱이 이 전화를 처리해주고 나는 그것을 받는다.Not Found에러입니다.
가장 좋은 해결책은 무엇입니까?발신하지 않는 모든 콜을 리다이렉트 하려고 합니다./api/v1/...로./이상적이지 않습니다.Respect 뷰가 아닌 앱의 홈 페이지로 돌아가기 때문입니다.
여기에는 catch-all URL을 사용했습니다.
from flask import Flask
app = Flask(__name__)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return 'You want path: %s' % path
if __name__ == '__main__':
app.run()
또한 1마일 더 나아가서 이 시스템을 재사용할 수 있습니다.Flask routing일치하는 시스템path클라이언트와 같은 루트로 전송되므로 클라이언트가 필요로 하는 데이터를 HTML 응답 내에 JSON으로 삽입할 수 있습니다.
어쩌면 전에 했던 대답의 연장선일지도 몰라.이것으로 문제가 해결되었습니다.
from flask import send_from_directory
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
path_dir = os.path.abspath("../build") #path react build
if path != "" and os.path.exists(os.path.join(path_dir, path)):
return send_from_directory(os.path.join(path_dir), path)
else:
return send_from_directory(os.path.join(path_dir),'index.html')
어떤 이유로 catch-all URL이 작동하지 않았습니다.플라스크 404 핸들러를 사용해도 똑같은 결과가 나온다는 것을 알았습니다.라우터는 URL을 확인하고 라우터가 처리하는 위치에 반응하기 위해 URL을 전달합니다.
@app.errorhandler(404)
def not_found(e):
return app.send_static_file('index.html')
핸들 에러 404와 render_template는 저에게 딱 맞습니다.
@app.errorhandler(404)
def not_found(e):
return render_template("index.html")
캐치올과 404 핸들러를 모두 조합해야 제대로 작동합니다.react-router에서 자체 리다이렉션핸들러를 사용하여 서브패스로 react-app을 호스트하고 있습니다.
@app.route('/sub-path', defaults={'path': 'index.html'})
@app.route('/sub-path/<path:path>')
def index(path):
return send_from_directory('../react-dir/build', path)
@app.errorhandler(404)
def not_found(e):
return send_from_directory('../react-dir/build','index.html')
언급URL : https://stackoverflow.com/questions/30620276/flask-and-react-routing
'programing' 카테고리의 다른 글
| 'System' 메서드로 시도합니다.Web. 도우미.Json..cctor()를 사용하여 메서드 'System'에 액세스합니다.Web. 도우미.Json.CreateSerializer()가 실패했습니다. (0) | 2023.03.16 |
|---|---|
| ref='string'은 왜 "disclosed"입니까? (0) | 2023.03.16 |
| Angular에서 서비스를 조롱하려면 어떻게 해야 합니까?재스민으로 유닛 테스트 할 때 JS? (0) | 2023.03.16 |
| Ajax 성공 및 오류 함수 오류 (0) | 2023.03.16 |
| 같은 서버상의 다른 포트는 크로스 도메인으로 간주됩니까?(Ajax-wise) (0) | 2023.03.16 |