如何使用 Flask 后端 API 构建 Angular 2 前端应用程序?

Sai*_*zir 3 ubuntu nginx flask gunicorn angular

我想使用 Nginx 为前端 Angular 2 应用程序提供服务。我使用 Gunicorn 作为 Nginx 和 Flask 之间的媒介。我想部署此 Web 应用程序进行生产。正确的应用程序结构应该是什么?另外,nginx 服务器块配置是什么?我托管在基于 Linux 的数字海洋 Droplet(Ubuntu 16.04)上。我引用了以下链接,但他们似乎也使用 Flask 来为前端提供服务。
https://www.digitalocean.com/community/tutorials/how-to-struct-large-flask-applications
https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with -gunicorn-and-nginx-on-ubuntu-16-04

Mel*_*kor 5

这是一个示例 Nginx 配置文件。我确信这不是最好的方法,但它让我测试了我的应用程序。

    server {
        listen       80;
        server_name  localhost;

        # Your angular app
        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
            try_files $uri $uri/ =404;
        }

        # Static files 
        location /static {
            alias /usr/share/nginx/flask/static;
        }

        # Gunicorn 
        location /api {
            proxy_pass http://localhost:4000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }   
    }
Run Code Online (Sandbox Code Playgroud)

注意事项

  1. 使用 Angular CLI 构建 Angular 应用程序(例如dist文件夹)。让 nginx 指向它。如/usr/share/nginx/html配置中所示。这个链接帮助我更好地了解 Angular CLI。

  2. 使用 Gunicorn 为您的烧瓶后端提供服务。说,gunicorn -b 127.0.0.1:4000 app:app。路由到/api.

  3. 配置 nginx 以反向代理到gunicorn。代码中给出。

希望这至少能让你继续前进。