使用 Apache 服务器时,Angular 应用程序在页面刷新时渲染后端数据

问题描述 投票:0回答:2

我正在尝试使用 Apache 部署演示 Angular Flask 应用程序。我的项目目录是/var/www/backend/basicapp/。该目录包含:

应用程序.py

from flask import Flask, jsonify, render_template
from flask_cors import CORS, cross_origin

app = Flask(__name__)


CORS(app)

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
   return app.send_static_file('index.html')

@app.route('/facts')
def facts():
   return jsonify("Honey never spoils. Archaeologists have found pots of honey in ancient Egyptian tombs that are over 3,000 years old!")

@app.route('/jokes')
def jokes():
   return jsonify("Why don't scientists trust atoms? Because they make up everything!")

if __name__=='__main__':
    app.run()

app.wsgi

import sys
import logging
sys.path.insert(0, '/var/www/basicapp/backend')

from app import app as application

此外,该目录还包含一个 **static ** 文件夹,我在其中放置了 Angular 的所有构建文件。这个静态文件夹还包含index.html 文件,您可以在基本路由中看到该文件。

这是我在 Apache 的 httpd.conf 文件中的虚拟主机配置:

<VirtualHost *:80>
  ServerName 192.170.160.71

  WSGIDaemonProcess basicapp user=apache group=apache threads=5
  WSGIScriptAlias /basicapp /var/www/basicapp/backend/app.wsgi

  <Directory /var/www/basicapp/backend>
    WSGIProcessGroup basicapp
    WSGIApplicationGroup %{GLOBAL}
    Require all granted
  </Directory>

  ErrorLog /var/www/basicapp/backend/logs/error.log
  CustomLog /var/www/basicapp/backend/logs/access.log combined

</VirtualHost>

现在,当我启动 apache 服务器并转到 192.170.160.71/basicapp/ 时,我可以在 UI 上看到我的主页。同样,当我转到 192.170.160.71/basicapp/facts/ 和 192.170.160.71/basicapp/jokes/ 时,我可以看到相应的页面正在 UI 上呈现。 但是,当我转到这两条路线(192.170.160.71/basicapp/facts/ 和 192.170.160.71/basicapp/jokes/)并刷新页面时,我看到的后端数据为JSON 显示在屏幕上。基本上,它不是显示我用 Angular 编写的前端 html 和 CSS,而是显示后端 json 消息,就像 /facts 路由或 /jokes 路由的 app.py 文件中的显示方式一样。这种特殊的行为仅在刷新页面时发生,我想避免这种情况。我哪里可能出错了?

它应该显示: correct behavior

但是刷新页面时,它会显示以下内容而不是用户界面: wrong behavior

请注意,只有刷新页面或直接进入路线时,才会突然显示后端数据。我在主页上有一个按钮可以转到事实路线,单击该按钮后,前端 UI 会正确显示。

最初,我只尝试了 render_template(index.html) 但这不起作用。然后我查看了 Flask 文档并发现了单页应用程序(SPA),我尝试将其添加到代码中,如您所见。但这也不起作用。

python angular apache flask mod-wsgi
2个回答
0
投票

或者,您可以在 Angular 应用程序中使用基于哈希的路由。这也应该可以解决问题。


0
投票

我的应用程序中前端和后端的 url 名称相同,这就是为什么存在名称冲突,导致后端数据渲染。基本上,为前端和后端保留单独的 url 名称解决了问题。

© www.soinside.com 2019 - 2024. All rights reserved.