Search code examples
pythonangularazureflaskflask-cors

CORS error when I deploy my app to flask and try to consume it by angular


I am working on an integration between azure, flask and angular, the question is that the CORS are blocking me and the notification appears in the console

these 3 situations happen:

  1. If the request is successful, the CORS error does not come out
  2. if the request fails, the CORS error does appear
  3. In my angular component, even though I have a console.log variable, it does not print in any of the situations in point 1 and 2

**FLASK CODE **

from flask import Flask, request
from flask_cors import CORS, cross_origin
import subprocess, re

app = Flask(__name__)
CORS(app, resources={r'/*': {'origins':'http://localhost:4200'}})

subscription_id = '<subscription_id>'
credentials = ServicePrincipalCredentials(
    client_id='<client_id>',
    secret='<client_secret>',
    tenant='<tenant_id>'
)
network_client = NetworkManagementClient(credentials, subscription_id)

@app.route('/create_listener', methods=['POST'])
@cross_origin(origins=['http://localhost:4200'])
def create_listener():
    #resource_group = "1234"
    #app_gateway_name = "1234"
    #listener_name = "Prob-2804v4"
    #frontend_ip_name = "Private"
    #frontend_port = "443"
    #ssl_certificate = "resourceGroups//providers/Microsoft.Network/applicationGateways/sslCertificates/"
    #host_name = "prob.websites.co"
    
    cmdCreate = f"az network application-gateway http-listener create --resource-group {resource_group} --  gateway-name {app_gateway_name} --frontend-port {frontend_port} --name {listener_name} --frontend-ip {frontend_ip_name} --host-names {host_name} --ssl-cert {ssl_certificate}"
    output = subprocess.check_output(cmdCreate, shell=True)

    return 'Listener created'

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

**ANGULAR CODE **

`import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-create-listener',
  templateUrl: './create-listener.component.html',
  styleUrls: ['./create-listener.component.css'],
})
export class CreateListenerComponent {
  data: any;
  resource_group: string | undefined;
  app_gateway_name: string | undefined;
  listener_name: string | undefined;
  frontend_ip_name: string | undefined;
  frontend_port: string | undefined;
  ssl_certificate: string | undefined;
  host_name: string | undefined;

  constructor(private router: Router, private http: HttpClient) {}

  sendDataListener() {

    const body = {
      resource_group: this.resource_group,
      app_gateway_name: this.app_gateway_name,
      listener_name: this.listener_name,
      frontend_ip_name: this.frontend_ip_name,
      frontend_port: this.frontend_port,
      ssl_certificate: this.ssl_certificate,
      host_name: this.host_name,
    };

    this.http
      .post<any>('http://127.0.0.1:5000/create_listener', body)
      .subscribe({
        next: (response) => {
          console.log(response);
          console.log('I´M HERE!!!');
          this.data = JSON.stringify(response);
          localStorage.setItem('data', this.data);
        },
        error: (err) => {},
      });
  }
}`

If you could help me correct why this cors error is happening when the request fails or if I am failing something in the logic, additionally know why the console.logs are not printed

I was looking in several places and they always used the cross origin notations in the code in the sectors where it is currently and also the same Flask documentation, additionally I don't know if I am sending the "body" in the best way since as I mentioned when sending the request in this case the listener is created but when making an error on purpose the error appears

I request through POST a JSON that must contain the variables that I require, in the code they are "burned" but it is only for practical purposes


Solution

  • this.http.post<any>('http://127.0.0.1:5000/create_listener', body).subscribe({
      next: (response) => {
        console.log(response);
        console.log('I´M HERE!!!');
        this.data = JSON.stringify(response);
        localStorage.setItem('data', this.data);
      },
      error: (err) => {
        console.log(err);
      }
    });
    

    this will log any error messages to the console, allowing you to see any CORS errors that are occurring.

    As for the console.log statements not printing, it's possible that the sendDataListener function isn't being called. You can try adding a console.log statement at the beginning of the function to verify that it's being called.

    Regarding the body, the way you're sending it in the request is correct. You're sending a JSON object in the request body, which will be accessible in your Flask code using the request.json property.

    I hope this helps you resolve your CORS issues and debugging the console.log statement.