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

Unusual problem with accessing Object values in vscode using typescript

When attempting to write Object.values in TypeScript, I encounter a visual error (although it compiles without issues). https://example.com/image1.png I have tried searching online and restarting vscode, and here is my current tsconfig.json. https://exa ...

Importing Json in Angular 8: A detailed guide

I recently came across information that you can now directly import JSON in TypeScript 2.9 and made changes to my tsconfig.json file accordingly: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", " ...

In Ionic 2, trying to access the IONIC_ENV variable consistently results in it being undefined

Does anyone know how to access the IONIC_ENV variable in order to switch between using the API URL for production and development environments? Every time I try to check it, it returns undefined. process.env.IONIC_ENV I might need to run or add another c ...

Error message displaying Angular Service not able to be injected into component: StaticInjectorError in AppModule

I'm currently attempting to inject a SpotifyService service into a SearchComponent component, where the service requires Http as a parameter. Below is my module setup: @NgModule({ imports: [ BrowserModule, FormsModule, RouterModule ], decla ...

Mat-button click event is unresponsive when Mousemove is triggered on a smartphone using material.angular

I have encountered an issue with Angular Material. Everything works smoothly on a desktop browser, but when using a smartphone or developer tools in Chrome, I noticed that the (click) event of a button does not fire if you move the cursor even by just one ...

Guide on utilizing tslint in conjunction with npx

I currently have tslint and typescript set up locally on my project. In order to run tslint against the files, I am using the following command: npx tslint -c tsconfig.json 'src/**/*.ts?(x)' However, when I run this command, it seems to have no ...

Implementation of Asp.Net core identity combined with Angular 2

Recently, I developed a web-app using Asp.Net with angular2. To kickstart the project, I utilized generator-aspnetcore-spa. Now, my next step is to integrate identity management into the application. After some consideration, I have decided to go with Asp ...

The optional parameters could not be obtained

After reading through the Angular documentation, it seems that I should be able to retrieve a route's options parameters from route.paramMap. However, when I attempt to log out the params, I am getting an empty object in return. I am developing a log ...

Asynchronously download static images with the power of NextJS and TypeScript integration

I have a query regarding my website development using NextJS and TypeScript. The site features a showcase gallery and is completely static. Currently, the initial view shows thumbnails of images. When clicking on a thumbnail, the original image is display ...

Issue arises when attempting to use the useEffect hook in React with Typescript to reset states upon the component unmounting

I'm facing an issue with my useEffect cleanup when the component unmounts and setting states simultaneously. My code involves selecting a client by clicking on them and setting their ID to send in an API request: const setClient = () => { setC ...

Exploring the features of NextJS version 13 with the benefits

Starting from the 13th step, SSR is utilized by default and in order to opt for client side rendering you must specify it at the top like so: 'use client' Currently, my setup involves TypeScript and styled-component integration. Take a look at ...

Exploring the differences between Angular's @Input and @Output directives and utilizing Injectable Services

When considering the differences between @Input/@Output in parent and child components versus using services that are instantiated only once with dependency injection (@Injectable()), I find myself questioning whether there are any distinctions beyond the ...

Concerns with combining key value pairs in Typescript Enums

Could you help me figure out how to properly implement an enum in my drop-down so that I can only display one value at a time? Currently, I am seeing both the key and the value in the list. This is my enum: export enum VMRole { "Kubemaster" = 0, "Kub ...

Tips for properly formatting a fixed table header

I'm currently facing an issue with the sticky header style in my data table. I have created a simple Angular component along with a specific directive: sticky.directive.ts @Directive({ selector: '[sticky]' }) export class StickyDirecti ...

Angular 8 feature module routing encompasses various components working together collaboratively

I am currently working on integrating a main module and a feature module that consists of various components. Below, I have provided the configuration for multiple routes within the feature routing file. const priorityRoutes: Routes = [ { path: &a ...

Guide to accessing component methods within slots using the Vue 3 Composition API

I have child components within a slot in a parent component and I am trying to call methods on them. Here are the steps I followed: Use useSlots to retrieve the child components as objects Expose the method in the child component using defineExpose Call t ...

Guidelines for returning an object upon finishing the .map function within a promise-based function in Node.js

While working on server-side code using nodejs, I have encountered an issue with the .map() method inside a Promise. The problem is that the method returns a value before the .map() function completes its execution successfully. Here's the snippet of ...

Error: The function webpackMerge.strategy does not exist

I've been in the process of updating an older Angular project to the latest version of Angular. However, I'm encountering a problem when trying to build, and I'm unsure why this is happening. Below is the error message that I've receiv ...

Integrating a fresh attribute into a Django model

Presently, I am immersed in a Django project involving approximately 30 models, with numerous relationships (such as foreign key associations) among them. I have a query: "Suppose I decide to add new field(s) to one of the models/tables in models.py after ...

Pattern Matching for Excluding Multiple Specific Phrases

I need to restrict what a user can enter into a field based on previous entries that are already in the system. For instance, the user has already entered these values into the database: ["typescript", "C#", "python"] If they type one of these existing ...