首页 > 解决方案 > CORS 配置 Flask、Angular 和 NGINX

问题描述

我正在尝试使用 nginx 将 Angular 应用程序上传到数字海洋水滴。这个应用程序使用烧瓶中的 API。在本地一切正常,但在 VPS 上无法正常工作。它说了一些关于Cross-origin request blocked: Same origin policy does not allow reading of remote resources at http://127.0.0.1:5001/api/talk/

这是我的 nginx 配置:

server {
    server_name x.domain.com;
    location / {
            proxy_pass http://127.0.0.1:4200;
            proxy_set_header Host x.domain.com;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protocol $scheme;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Origin "";
            add_header "Access-Control-Allow-Origin"  "*";
            add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
            add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    }
 }
 server {

    location / {
            proxy_pass http://127.0.0.1:5001;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protocol $scheme;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Origin "";
            add_header "Access-Control-Allow-Origin"  "*";
            add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
            add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    }

    location /api/talk/ {
            proxy_pass http://127.0.0.1:5001;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protocol $scheme;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Origin "";
    }

    location /api/response/ {
            proxy_pass http://127.0.0.1:5001;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Protocol $scheme;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Origin "";
    }
 }

这是我的烧瓶配置:

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

chat = Chat()


@app.route('/api/talk/', methods=['POST'])
@cross_origin(origin='localhost')
def index():
  print(request.data.decode("utf-8"))
  chat.send_message(request.data)
  return request.data


@app.route('/api/response/', methods=['GET'])
@cross_origin(origin='localhost')
def get():
  response = chat.response
  return response


def options(self):
  return {'Allow': 'POST'}, 200, \
    {'Access-Control-Allow-Origin': '*',
     'Access-Control-Allow-Methods': 'POST,GET'}


if __name__ == '__main__':
  app.run(host='127.0.0.1', port=5001, debug=True)

并且 Angular 在这里使用烧瓶 API:

export class Message {
  constructor(public content: string, public sentBy: string){ }
}

@Injectable({
  providedIn: "root",
})
export class MessageService {
  conversation = new BehaviorSubject<Message[]>([]);
  readonly SERVER_URL = "http://127.0.0.1:5001";
  public httpClient = axios.create();

  constructor(){}

  update(msg: Message) {
    this.conversation.next([msg]);
  }

  converse(msg: string) {
    const userMessage = new Message(msg, 'user');
    this.update(userMessage);
    this.sendMessage(userMessage.content)
  }

  sendMessage(msg: string) {
    console.log(msg)
    const config = {
    headers: { 
      'Content-Type': 'text/plain',
      'Access-Control-Allow-Headers': 'Content-Type',
      'Access-Control-Allow-Methods': 'GET POST',
      'Access-Control-Allow-Origin': '*'
    },
  };
  this.httpClient.post(this.SERVER_URL+'/api/talk/', btoa(msg), config)
    .then(function (response) {
  })
  .catch(function (error) {
     console.log(error);
   });
 }

 async getResponse() {
  await this.delay(900);
  let msg = ''
  return this.httpClient.get(this.SERVER_URL+'/api/response/')
  .then(response => {
     msg = response.data
     const botMessage = new Message(msg, 'chucho');
     this.update(botMessage);
     return msg
  })
  .catch(function (error) {
    console.log(error);
  });
}

 delay(ms: number) {
   return new Promise( resolve => setTimeout(resolve, ms) );
 }  
}

我的 Angular 应用程序在 4200 端口上运行,而 Flask API 在 5001 端口上。

希望您能够帮助我。

标签: angularapinginxflaskcors

解决方案


尝试像这样启用 CORS -

但首先通过运行安装最新的烧瓶 -

pip install -U flask-cors

from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app) # This will enable CORS for all routes

@app.route("/")
@cross_origin()
def helloWorld():
  return "Helloworld!"

推荐阅读