Angular 路由器未使用 ng build 与 Flask 服务器交互

Angular router not engaging with Flask server using ng build

在 Flask 和 ng build --aot --watch 中使用 Angular 5 时,我在获取 Angular 的路由和刷新页面时遇到了重大问题。

我遇到过很多解决此问题的尝试,但是 none 将它们应用到我的项目工作中(我在那里尝试时提供的示例项目似乎也不起作用)。

会发生什么(取决于我尝试的事情)是这些:

  1. 根本找不到路径,出现 Jinja2 错误
  2. 找不到 localhost:5015/(我正在使用的端口)的文档,我收到 404 和白屏
  3. 它加载 index.html,但在刷新时得到 404(暗示浏览器正试图从服务器获取页面,而不是使用 Angular 路由系统)
  4. 我遇到了与此问题相同的问题:

我的印象是这是所有 SPA 的正常问题,解决方案是始终将服务器重定向到 index.html。我们已经这样做了(AFAIK),并尝试了多种方法来做到这一点: 我们的结构大致如下:

- ProjectDir
  - reverseProxy_Calls
  - scripts
  - swagger_yaml_definitions
  - templates
    - e2e
    - dist
    - src
      - app

我们的 server.py 包含这个(以及其他内容)

Swagger(app)

app.template_folder = "./templates/dist/"
app.static_folder = "./templates/dist/"
app.static_path = "./templates/dist/"
app.static_url_path = "./templates/dist/"
app.instance_path = "./templates/dist/"
config = settings.config()
config.read("settings.cfg")


@app.route('/', defaults={'path': ''}, methods=['GET', 'POST'])
@app.route('/<path:path>', methods=['GET', 'POST'])
def get_resource(path):  # pragma: no cover
    # If we are devmode, proxy through flask.
    if config.getKey("devmode") == True:
        url = "http://localhost:%s/%s" % (config.getKey('ng_port'), path)
        j = requests.get(url, stream=True, params=request.args)
        return make_response(j.text)
    # return the results
    # return render_template('dist/index.html')
    # return app.send_static_file("index.html")
    return send_from_directory('dist/', path)

if __name__ == '__main__':
    app.run(debug=True, port=int(config.getKey("port")))  # , host='0.0.0.0')

^ 此处的各种方式显示了处理此问题的各种尝试。

我还查看并尝试了使用以下变体的项目:

None 我试过后都解决了这个问题

有人告诉我,在 Angular 中使用 hashRoute 位置策略而不是 History PushState 策略也可以,但是当我尝试这样做时,它具有相同的行为,即在刷新时丢失页面 (此外,我们希望在未来使用服务器端渲染,而 hashRoute 定位策略可以防止这种可能性,以及许多其他缺点)。

可能相关的是,当 Flask 确实找到 index.html 和最初的路由时,它似乎会重新加载或重新呈现页面,擦除打印到浏览器开发控制台的任何内容。我在一些烧瓶示例中看到了这一点,但不是全部,我不确定是什么原因造成的。

当 运行 通过 ng serve --aot --prod 时,一切都按预期正常工作。只有当通过 Flask 服务时,事情才会崩溃。

很抱歉问题很长,感谢您提前抽出时间。

I am under the impression this is a normal issue with all SPAs and that the solution is to always redirect the server to index.html. We have done this (AFAIK), and attempted multiple ways to do this

您还需要将所有 HTTP 错误重定向到 index.html