Potential solution for communication issue between Angular CLI and Flask due to cross-origin error

Initially, the user id and password are submitted from the UI (angular) to Flask:

  public send_login(user){
           console.log(user)
           return 
     this.http.post(this.apiURL+'/login',JSON.stringify(user),this.httpOptions)
    .pipe(retry(1),catchError(this.handleError))
     } 

Subsequently, it is received from the backend.

Backend Error

While all operations are functioning correctly, a cross-origin error is appearing in the console.

Error at UI Console

The HTTP options on the UI side are as follows:

constructor(private http: HttpClient) { }
  // Http Options
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': 'http://localhost:9000',
      'Access-Control-Allow-Methods': "GET,POST,OPTIONS,DELETE,PUT",
      'X-Requested-With': 'XMLHttpRequest',
      'MyClientCert': '',        // This is empty
      'MyToken': '' 
    })
  }

The CORS declaration in the backend is stated below:

cors = CORS(app, resources={r"/login": {"origins": "*"}})
 @app.route('/login', methods=['GET','POST'])
 def loginForm():
 json_data = ast.literal_eval(request.data.decode('utf-8'))
  print('\n\n\n',json_data,'\n\n\n')

I am unable to pinpoint where the issue is arising.

Note: The cross-origin error occurs during the login process, but not in subsequent steps.

Answer №1

Add the following code snippet to your app.py file:

CORS(app, supports_credentials=True)

Additionally, on the frontend side, make sure to use:

{with-credentials :true}

This will facilitate communication between the frontend and backend of your application.

Answer №2

In my opinion, it appears that the call is not getting through to the front end (based on my personal experience) because the browsers are implementing security measures.

To address this issue, you should create a new file named proxy.conf.json within the src/ directory of your project.

{
  "/backendApiUrl": {      <--- Ensure this points to the server backend base path
    "target": "http://localhost:9000",    <-- This represents the backend server's host and port
    "secure": false,
    "logLevel": "debug"    <--- Optionally, for additional debug information
  }
}

In your angular.json file (CLI configuration), include the following proxyConfig setting in the serve target:

"projectname": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy.conf.json"      <--- Vital addition here
    },

Now, simply execute ng serve command to run the development server using this configured proxy setup.

If you require more detailed information, refer to the section titled Proxying to a backend server at https://angular.io/guide/build

I trust this explanation will be beneficial to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the best practices for utilizing the error prop and CSS with the Input API in Material UI while utilizing context

When working with the MUI Input API props and CSS, I encountered an issue related to the {error} and its use. This is how my code looks: const [value, setValue] = useState<string>(cell.value); const [startAdornment, setStartAdornment] = useState< ...

Utilizing a Link element in conjunction with ListItem and Typescript for enhanced functionality

I am currently using material-ui version 3.5.1 My goal is to have ListItem utilize the Link component in the following manner: <ListItem component={Link} to="/some/path"> <ListItemText primary="Text" /> </ListItem> However, when I tr ...

Unsure about the best method for limiting routes within the meanjs framework

I am fairly new to using the MEAN stack for development. The app I am currently working on was scaffolded out using meanjs and yeoman. My goal is to have both regular users and administrators in the system, with admins being able to manage all users (crea ...

acquiring the URL link following a search

When trying to extract the hrefs from a page after a successful search, I encountered an issue. enter = present (driver, By.CSS_SELECTOR, "#search-submit") driver.execute_script ("arguments[0].click()", enter) elems = driver.find_elements_by_xpath ("//a[ ...

Can a ternary operator be used within an index type query when extending a partial type?

Can anyone provide a detailed explanation of the process unfolding in this snippet? I'm having trouble grasping how this code leads to a type declaration. type ModalErrors = Partial< { [key in keyof InputGroup]: InputGroup[key] extends Speci ...

Unable to assign unique identifiers to elements within a user interface framework

I am having difficulty assigning an id to components. Scenario 1: - Trying to assign an id to an HTML component. <h1 id="demo-h1">Demo Heading</h1> Assigning id to HTML component Scenario 2: - Attempting to assign an id to a componen ...

Obtaining collision side of Pygame sprites - rect detection

I'm a beginner in pygame and I'm looking to gain some basic knowledge. My goal is to create obstacles and determine which side of the player rectangle (representing the collision box of the sprite) is colliding with the obstacle rectangle. This w ...

Angular 4 and the process of HTML encoding

Looking for assistance with html encoding in angular 4. I have product records stored in a database, with the fullDescription field in this particular format: &lt;div align="justify"&gt;&lt;span&gt; When using <div *ngIf="product" [inn ...

How to Efficiently Remove Array Elements by Index in Typescript

What is the best way to remove an item by its index using Typescript? For example: let myArray = ['apple', 'banana', 'cherry', 'date']; // How can I delete the item at index 2? ...

Resetting $urlRouterProvider.deferIntercept(); for AngularJS 1's UI Router

While working with Angular 1.5 and angular ui router, I encountered a challenge in altering the behavior of the back button on my app states. The issue arises when the state transitions between different URLs without refreshing the page. Despite implementi ...

A guide on incorporating Angular Material into a monolithic application in JHipster version 7.6.0

Hello everyone, I have an application built with jHipster 7.6.0 and I am trying to integrate Angular Material into it. When I run the command ng add @angular/material, I encounter this error: https://i.stack.imgur.com/J3ErS.png The issue I am facing wit ...

Experiencing difficulty creating query files for the apollo-graphql client

I'm currently attempting to learn from the Apollo GraphQL tutorial but I've hit a roadblock while trying to set up the Apollo Client. Upon executing npm run codegen, which resolves to apollo client:codegen --target typescript --watch, I encounter ...

The "(click)" event doesn't fire upon clicking a material icon

After creating an <a> tag with a (click) event function call, I noticed that the click event works everywhere except for the arrows mat-icons within the code snippet below: <span *ngIf="section.pages.length>0"> <mat-icon *ngIf="secti ...

Having trouble importing .task files in a Next.js project with TypeScript?

I encountered an issue when trying to import a model.task file into my App.tsx file. After training a hand gesture recognition model in Python, I exported it to a model.task file. Now, I am attempting to import this file into my Next.js + Typescript proje ...

Dynamically setting the IMG SRC attribute with the base64 result of a FileReader for file input

Looking for a little guidance on something new, I'll keep it brief because I'm sure it's just some small detail I'm overlooking... Starting with an image like this, where currentImage is the initial existing image path; <img src="{ ...

After using apt to install tsc, I find myself in a dilemma on how to either delete or upgrade it

After realizing I was missing Typescript on my server, I attempted to run the 'tsc' command. However, I received a message suggesting I use 'apt install tsc' instead. Without much thought, I executed the command. Normally, I would insta ...

Are there more efficient methods for utilizing local scope when defining a variable?

Having experience in the ML world, I'm used to creating variables with limited scope like this: let myVar = let result1 = doSomething() let result2 = doSomethingElse() result1 + result2 In TypeScript, it seems you can achieve similar sco ...

What is the proper way to define the type when passing a function as a component prop, with or without parameters?

import { dehydrate, HydrationBoundary } from '@tanstack/react-query'; import getQueryClient from '@/lib/react-query/getQueryClient'; export async function RQBoundary<T>({ children, queryKey, fn, }: { children: React.Reac ...

The return type of Array.find is accurate, however, it contains an error

Trying to find a way to indicate the expected return type of Array.find() in TypeScript, I encountered an incompatibility warning. View code in playground class A { "type"="A" t: string; #a = 0 constructor(t: string) { ...

Harmonize the connectivity between an Angular - .NET application and the Google Calendar API

I am currently working on integrating the Google Calendar API into my angular .NET application using OAuth2. The goal is to allow each user to see their own calendar as soon as they log in. One idea I have is to save the generated code into our database f ...