Azure vm 上的 Angular 烧瓶应用部署问题

时间:2021-07-08 11:40:20

标签: angular azure nginx flask cors

我的目标是将 Web 应用程序部署到 Azure VM。该代码在我的电脑上运行良好。

我有一个包含以下内容的代码:

  • Flask 应用作为后端服务器(机器学习应用)
  • Angular 应用程序作为与 Flask-server 连接的前端
  • 我有一个带有 DNS 的 Azure VM:guiss1.francecentral.cloudapp.azure.com

这是烧瓶的截取代码:

import time
import numpy as np
from reshaper import Reshaper
import flask
from flask import request, jsonify
import datetime
from flask_cors import CORS
from flask_pymongo import PyMongo
import guiss_utils
from flask_restful import  Api

old_slides = [0, 0, 0, 0, 0,
             0, 0, 0, 0, 0,
             0, 0, 0, 0, 0,
             0, 0, 0, 0, 0]
flag = 2
bodyf = Reshaper(label="female")
bodym = Reshaper(label="male")

app = flask.Flask(__name__)
CORS(app)

cors = CORS(app, resources={
   r"/*": {
       "origins": "*"
   }
})


app.config["MONGO_URI"] = "mongodb://localhost:27017/myDatabase"
mongo = PyMongo(app)
res_fares = {}

mongo.db.users.remove()

@app.route('/api/form-example', methods=['POST'])
def form_example():
   if request.method == 'POST':
       some_json = request.get_json()
       print(some_json)

       if not (mongo.db.users.find_one(
               {"id": some_json['id'], 'weight': some_json['weight'], 'height': some_json['height'],
                'gender': some_json['gender']})):
           res_fares1 = guiss_utils.create_avatar(float(some_json['weight']), float(some_json['height']),
                                                  some_json['gender'])
           size = guiss_utils.size_set(res_fares1['value'])
           user_collection = mongo.db.users
           _id = user_collection.insert(
               {'avatar': res_fares1['avatar'], 'comb': res_fares1['comb'], 'value': res_fares1['value'], 'size': size,
                't_data': res_fares1['t_data'], 'id': some_json['id'],
                'weight': some_json['weight'], 'height': some_json['height'], 'gender': some_json['gender'],
                'name': some_json['name'], 'surname': some_json['surname'], 'date': datetime.datetime.today(),'oldslider':old_slides}
           )
       # else:
       #     user_collection = mongo.db.users
       #     _id = user_collection.update_one({"id": some_json['id']}, {
       #         "$set": {'oldslider':old_slides}}, upsert=True)

       return jsonify({}), 201





@app.route('/api/form-example1', methods=['POST'])
def form_example1():
   if request.method == 'POST':
       some_json = request.get_json()
       id2 = some_json['id']
       post = mongo.db.users.find_one({"id": id2})
       del post['_id']
       t_data = post['t_data']
       old=post['oldslider']

       mesh, t_data,new_slides = guiss_utils.update_shape(t_data, some_json['i'], some_json['val'], some_json['gender'],old)

       avatar = {'vertices': (mesh.vertices.flatten()).tolist(), 'indexes': (mesh.faces.flatten()).tolist()}

       user_collection = mongo.db.users
       _id = user_collection.update_one({"id": id2}, {
           "$set": {'avatar': avatar, 't_data': t_data,'oldslider':new_slides}}, upsert=True)
       return jsonify({}), 201


@app.route('/api/setsize', methods=['POST'])
def setsize():
   if request.method == 'POST':
       some_json = request.get_json()
       id2 = some_json['id']
       post = mongo.db.users.find_one({"id": id2})
       del post['_id']
       mm = post['avatar']
       value = guiss_utils.calc_measure(guiss_utils.cp, np.array(mm['vertices']).reshape((-1, 3)),
                                        np.array(mm['indexes']).reshape((-1, 3)))
       size = guiss_utils.size_set(value)
       comb = []
       for i, key in enumerate(guiss_utils.M_STR):
           comb.append({'name': key, 'size': round(value[i], 2)})

       user_collection = mongo.db.users
       _id = user_collection.update_one({"id": id2}, {
           "$set": {'comb': comb, 'value': value, 'size': size}}, upsert=True)
   return jsonify({}), 201

@app.route('/api/returndata/<int:id2>', methods=['GET'])
def returndata(id2):
   if request.method == 'GET':
       post = mongo.db.users.find_one({"id": id2})
       del post['_id']
       return jsonify(post), 201


@app.route('/api/getlastid', methods=['GET'])
def getlastid():
   if request.method == 'GET':
       post = mongo.db.users.find()

       id = 0
       for p in post:
           id = p['id']
       return jsonify(id), 201


@app.route("/api")
def index():
   return "<h1>Hello!</h1>"

if __name__ == '__main__':
   print("The application is working")
   app.run(debug=True,host='0.0.0.0', port='5000')

wsgi.py 的代码:

from guiss_api import app

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

这是angular app的截取代码,负责路由的:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { from, Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';


@Injectable({
 providedIn: 'root'
})

export class AvatarsimpleService {
 base_path  = 'http://0.0.0.0/5001/api';

 constructor(private http: HttpClient) { }


   // Handle API errors
   handleError(error: HttpErrorResponse) {
     if (error.error instanceof ErrorEvent) {
       // A client-side or network error occurred. Handle it accordingly.
       console.error('An error occurred:', error.error.message);
     } else {
       // The backend returned an unsuccessful response code.
       // The response body may contain clues as to what went wrong,
       console.error(
         `Backend returned code ${error.status}, ` +
         `body was: ${error.error}`);
     }
     // return an observable with a user-facing error message
     return throwError(
       'Something bad happened; please try again later.');
   }


     // Create a new item
     createItem(item :any): Observable<any> {
       //console.log(item)
       return this.http
         .post<any>(this.base_path+ '/form-example' , item)
         .pipe(
           retry(2),
           catchError(this.handleError)
         );
     }

     createItem1(item :any): Observable<any> {
       //console.log(item)
       return this.http
         .post<any>(this.base_path+ '/form-example1' , item)
         .pipe(
           retry(2),
           catchError(this.handleError)
         );
     }

           // Create a new item
           createsize(item :any): Observable<any> {
             //console.log(item)
             return this.http
               .post<any>(this.base_path+ '/setsize' , item)
               .pipe(
                 retry(2),
                 catchError(this.handleError)
               );
           }

     createimage(id:any,item :any): Observable<any> {
       //console.log(item)
       return this.http
         .post<any>(this.base_path+ '/im-example'+ '/' + id , item)
         .pipe(
           retry(2),
           catchError(this.handleError)
         );
     }

           // Get single student data by ID
   getItem(id:any): Observable<any> {
     return this.http
       .get<any>(this.base_path+ '/returndata'+ '/' + id)
       .pipe(
         retry(2),
         catchError(this.handleError)
       );
   }

   getId(): Observable<any> {
     return this.http
       .get<any>(this.base_path + '/getlastid')
       .pipe(
         retry(2),
         catchError(this.handleError)
       );
   }
}



这是我的 azure VM 的防火墙配置:

enter image description here

我所做的是:

  • 我像这样构建了我的 Angular 项目:
ng --build
mv dist/ /var/www/app
  • 我使用 gunicorn 部署了我的烧瓶应用
gunicorn --bind 0.0.0.0:5000 wsgi:app &
curl HTTP://0.0.0.0:5000/api/ ---> <h1>Hello!</h1>

我用 curl 测试过

  • 我这样配置 Nginx:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
       worker_connections 768;
       # multi_accept on;
}

http {

       server {

             listen       80;
             server_name  guiss1.francecentral.cloudapp.azure.com;
             charset utf-8;

             location / {
                       root /var/www/app;
                       index index.html index.html;
                       try_files $uri $uri/ /index.html;
                }


             location /api {

           proxy_pass http://0.0.0.0:5000;
           proxy_set_header Upgrade    $http_upgrade;
           proxy_set_header Connection $http_connection;
           proxy_set_header Host       $host;
             }

       }

       ##
       # Basic Settings
       ##

       sendfile on;
       tcp_nopush on;
       tcp_nodelay on;
       keepalive_timeout 65;
       types_hash_max_size 2048;
       # server_tokens off;

       # server_names_hash_bucket_size 64;
       # server_name_in_redirect off;

       include /etc/nginx/mime.types;
       default_type application/octet-stream;

       ##
       # SSL Settings
       ##

       ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
       ssl_prefer_server_ciphers on;

       ##
       # Logging Settings
       ##

       access_log /var/log/nginx/access.log;
       error_log /var/log/nginx/error.log;

       ##
       # Gzip Settings
       ##

       gzip on;

       # gzip_vary on;
       # gzip_proxied any;
       # gzip_comp_level 6;
       # gzip_buffers 16 8k;
       # gzip_http_version 1.1;
       # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

       ##
       # Virtual Host Configs
       ##

       include /etc/nginx/conf.d/*.conf;
       include /etc/nginx/sites-enabled/*;
}

#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#       }
#
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}


前端工作正常(请随时检查 http://guiss1.francecentral.cloudapp.azure.com/ )。但是,当我尝试连接后端服务器时(网站中标题为“Démo”的部分),总是弹出CORS错误。

ERROR when I try to access my back-end server from the angular app

我尝试了以下解决方案:

#proxy.config.json
{
    "/api/*": {
        "target": "http://0.0.0.0:5001",
        "secure": false,
        "logLevel": "debug",
        "changeOrigin": true
    }
}

如果您需要其他任何东西,请告诉我。我尽力解释了一切。

0 个答案:

没有答案