Encountering issues with Proxy functionality in the latest versions of Angular 13 and Spring Boot

I've encountered an issue with the proxy configuration in Angular. I'm unsure if it's a problem within my Angular settings or if there's a configuration issue in Spring.

For testing purposes, I have a backend built in springboot to handle simple requests from the frontend. However, when attempting to make requests to the backend through Angular, I consistently receive a CORS error:

Access to XMLHttpRequest at 'http://localhost:8080/api/people/checks' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I've tried creating a proxy using Angular's Documentation but it seems like the proxy isn't functioning as expected.

proxy.conf.mjs

export default [
  {
    context: ['/api'],
    target: 'http://localhost:8080',
    secure: false,
    logLevel: 'debug',
    // pathRewrite: { '^/api': '' }
  }
];

angular.json

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "clubzin:build:production"
            },
            "development": {
              "browserTarget": "clubzin:build:development",
              "proxyConfig": "src/proxy.conf.mjs"
            }
          },
          "defaultConfiguration": "development"
        }

enviroments.ts

export const environment = {
  production: true,
  apiUrl: 'http://localhost:8080',
  username: 'danilo',
  password: '35bf85fe-c672-4d06-8cff-4485ed89211a',
  baseUrl: '/api'
};

people.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { CheckMail } from '../../home/model/check-mail';

import { environment } from '../../../environments/environment';

import { Buffer } from 'buffer';

@Injectable({
  providedIn: 'root'
})
export class PeopleService {

  private readonly API = `${environment.apiUrl}${environment.baseUrl}/people`;

  constructor(private httpClient: HttpClient) { }

  checkMailInUse(mail: string) {
    let credential = Buffer.from(`${environment.username}:${environment.password}`).toString('base64');
    let headers = { Authorization: 'Basic ' + credential, mail: mail };
    let data = this.httpClient.get<CheckMail>(`${this.API}/checks`, { headers });
    return data;
  }

}

My question now is, am I overlooking something? Or do I need to configure something in springboot as well?

NOTE: When adding the CORS annotation in the controller, the request works perfectly.

Answer №1

It seems that the issue does not lie within the code itself, but rather in the environment setup. The problem arises when running the backend on Windows and the frontend on WSL (Windows Subsystem for Linux). This causes a conflict where the proxy is unable to locate the backend when trying to access localhost. However, after transferring the code to run solely on Windows, the problem was resolved and the API started functioning as expected.

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

Experiencing difficulties with the mat-card component in my Angular project

My goal is to implement a login page within my Angular application. Here's the code I've written: <mat-card class="login"> <mat-card-content> <div class="example-small-box mat-elevation-z4"> ...

LocalStorage in Angular application failing to function in Android web view

Working with Angular 4, I've developed a web application that stores the user security token in localStorage after login. The application uses this localStorage value to control the visibility of certain links, such as hiding the login button once th ...

Tips for transferring TimeZone Name from Angular to .NET API

Currently, the API I am working with accepts TimeZone names (such as America/Denver) as a string. In my Angular UI application, I automatically pass the browser timeZoneName to the API. However, when the API receives the string America/Denver, it interpret ...

My HTML grid table is not being properly rendered by the JSON data

I'm currently facing a challenge with rendering my HTML grid table in Angular using JSON data retrieved from a MySQL database. I would greatly appreciate any assistance or guidance on how to solve this issue. View the output of the Angular code here ...

Vue Error: The method "reduce" is not a function

Currently implementing Vue.js with Typescript and aiming to utilize reduce for summing up the values of desktopCnt and mobileCnt from the deviceCount array to display their total numbers. The deviceCount array structure is as follows: [ { " ...

Running AngularJS within an Angular 8 application using ngUpgrade is not supported

Struggling to get my Hybrid Angular application up and running using ngUpgrade according to the documentation. The issue is that no matter what tweaks I make, AngularJS just won't cooperate. When I combine Angular and AngularJS, both applications wor ...

There is an error in the TypeScript code where it is not possible to assign a string or

I'm struggling to resolve a typescript error. Upon checking the console log, I noticed that the regions returned by Set are an array of strings, which aligns perfectly with the region type in my state. Why isn't this setup working as expected? S ...

Parsing the header parameter in a GET request from Angular within the Spring backend

Recently, I delved into Rest services in Spring and learned from a tutorial that sending parameters to the backend can be done securely through the following method: getCompanyDetails(username:string): Observable<CompanyObject>{ const headers = ...

Loop through every item in Typescript

I am currently working with the following data structure: product: { id: "id1", title: "ProductName 1", additionalDetails: { o1: { id: "pp1", label: "Text", content: [{ id: "ppp1", label: "Tetetet" ...

Is there a way to seamlessly transfer (optional) parameters from a CloudFormation template to a CDK resource within a CfnInclude without statically defining the list of parameters?

Trying to grasp these syntax rules, unsure if it's possible. We have numerous CloudFormation templates that we want to deploy using CDK by constructing them with CfnInclude. The issue is that CfnInclude always needs an explicit parameters argument if ...

What is the most recent stable version of Angular recommended for utilizing ui-bootstrap?

I've been working on updating an older angular application and I'm interested in incorporating ui bootstrap for more advanced features. However, the current version of Angular used is 1.2.18 and any attempt to upgrade it to a higher version resul ...

Iterating through elements within the ng-content directive in Angular using *ngFor

Is it possible to iterate through specific elements in ng-content and assign a different CSS class to each element? Currently, I am passing a parameter to enumerate child elements, but I would like to achieve this without using numbers. Here is an example ...

Guide on retrieving image file name and extension with camera plugin in Ionic 2

Hi everyone, I'm looking for a way to retrieve the image name with its extension using the camera plugin in Ionic 2. Any tips on how to achieve this? Thank you! Below is the code I have so far: // Function for selecting an image ImagePick() { ...

Need help inserting an image into the div when the ngif condition is true, and when the ngif condition is false

Essentially, I have a situation where I am using an *ngIf condition on a div that also contains an image. This is for a login page where I need to display different versions based on the type of user. However, I'm facing an issue where the image does ...

Error: The token 'export' in d3zoom is causing a syntax issue

I'm encountering issues with executing tests in Angular: ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export {default as zoom} from "./zoom.js"; ...

How can I use Laravel to enter data using the post method?

I've been struggling with data transfer in my Angular component for a while now, specifically using a post method. Despite extensive research and reading various documents, I haven't been able to find a solution. Can you assist me with this issue ...

Angular is expecting data of type string or number for the operands provided

When working in VS Code, I encountered the following warning: "Expected operands to be a string or number type" https://i.stack.imgur.com/lULLQ.png The contentType variable is defined as a string. I noticed that when I remove 'data:', every ...

When I try to ng build my Angular 11 application, why are the type definitions for 'Iterable', 'Set', 'Map', and other types missing?

As someone new to Angular and the node ecosystem, I'm facing a challenge that may be due to a simple oversight. The issue at hand: In my Angular 11 project within Visual Studio 2019, configured with Typescript 4, attempting to run the project throug ...

Steps for adjusting the status of an interface key to required or optional in a dynamic manner

Imagine a scenario where there is a predefined type: interface Test { foo: number; bar?: { name: string; }; } const obj: Test; // The property 'bar' in the object 'obj' is currently optional Now consider a situatio ...

Exploring the benefits of using getServerSideProps with NextJS and Typescript for

Dear community, I am facing a challenge with integrating NextJS Layout and Typescript. Although everything seems to be working fine, I can't seem to get rid of the squiggly line under the props when passing them from getServerSideProps. The prop {som ...