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

Display a loading indicator when loading a lazy loaded module in Angular 2

Here's my situation: I have a menu with various options that should be displayed based on user permissions. The majority of the menu items are contained within modules, and these modules are lazy loaded. This means that when a user clicks on a menu it ...

Discover how Angular 8 allows you to access a method result from a child component in the parent component using ViewChild once the method has been called in the

In my child component, I have implemented two buttons as shown below: child-component.html <div> <button (click)="getFirstData()">First</button> <button (click)="getLastData()" >Last</button> </div> In child-com ...

Encountering type errors in NextJS with TypeScript

I am facing an issue while trying to run this function: "use server"; export const addProduct = async (formData: FormData, imageUrl: string) => { const productName = formData.get("productName")?.toString(); const description = f ...

Using Angular to make a request to a NodeJS+Express server for a simple GET operation

I need help with making a successful GET request from my Angular component to a NodeJS+Express server. someComponent.ts console.log("Before"); // send to server console.log(this.http.get('/email').map((res:Response) => { console.log(" ...

Facing problem with Angular 7 when making a GET request for non-JSON data

Currently, I am retrieving JSON data from a URL using the following method: this.http.get('http://localhost:3200/mydata').subscribe(data => { console.log(data); }); The response is in JSON format, and everything seems to be working fine. ...

Utilizing Shadow Root and Native Web Components for Seamless In-Page Linking

An illustration of this issue is the <foot-note> custom web component that was developed for my new website, fanaro.io. Normally, in-page linking involves assigning an id to a specific element and then using an <a> with href="#id_name&quo ...

Error message encountered when trying to associate "can" with an ability instance within Types

Just copying example code from documentation import { createCanBoundTo } from '@casl/react'; import ability from './abilities'; export const Can = createCanBoundTo(ability); An error occurs on the last line: The exported variable & ...

Having trouble customizing the toolbar on ngx-quill? Quill seems to be having trouble importing modules

UPDATE: I jumped ship when I discovered that PrimeNg had a quill implementation, and since I was already using PrimeNg, I switched over. Initially had some issues, but upgrading to angular 7 and ngrx 7 beta resolved them. https://www.primefaces.org/primeng ...

Unable to trigger an alert within a function in Ionic 4

I need to display an alert within a function that is using Firebase authentication. This is my TypeScript code (with jQuery enabled): async showEmptyAlert() { const empty = await this.alertController.create({ header: 'Error!', m ...

The output of switchMap inner will generate an array similar to what forkJoin produces

I have a series of observables that need to run sequentially, with each result depending on the previous one. However, I also need all the intermediate results in an array at the end, similar to what is achieved with the use of forkJoin. Below is the curr ...

Experimenting with a VSCode extension that requires the act of launching a folder/workspace

Currently, I am developing a custom VSCode extension that considers the path of the file being opened within the workspace. To create a reproducible test scenario, I want to open the test folder itself in VSCode and then proceed to open the test file with ...

What is the reason behind Flow's reluctance to infer the function type from its return value?

I was anticipating the code to undergo type checking within Flow just like it does within TypeScript: var onClick : (() => void) | (() => boolean); onClick = () => { return true; } However, I encountered this error instead: 4: onClick = () => ...

Creating a function in Angular to locate each object based on its ID

Hello there, I am currently working on creating a method called findChildByIdInData(data:any, childId:string). This method will take in a JSON main node with children that have unique IDs, and the goal is to find a specific object based on the ID provided ...

Tips on preserving type safety after compiling TypeScript to JavaScript

TS code : function myFunction(value:number) { console.log(value); } JS code, post-compilation: function myFunction(value) { console.log(value); } Are there methods to uphold type safety even after the conversion from TypeScript to JavaScript? ...

Exploring the functionality of the WHERE function in Firebase with Angular

Current Objective: Our main focus here is to allow users to post within their designated Organization Group. These posts should remain exclusively visible within the specific Organization Group they are posted in. To achieve this, I have attempted to impl ...

Attempting to simulate the behavior of nfcManager by utilizing the nfcManager.start() function in react native testing library

In the process of developing my Android app, I encountered a need to read NFC tags. To accomplish this task, I decided to utilize the react-native-nfc-manager library. However, during my implementation, I faced two perplexing issues that have left me stump ...

I am looking to append a new value to an array within the state in React

development environment ・ react ・ typescript In this setup, state groups are stored as arrays. If you want to add a group to the array of groups when the onClickGroups function is called, how should you go about implementing it? interface ISearc ...

What are the best methods for protecting a soda?

My code is in strict mode, and I am encountering an issue with the following snippet: const a: string[] = []; // logic to populate `a` while (a.length > 0) { const i: string = a.pop(); // This line is causing an error console.log(i); // additio ...

Utilize Material icons in CSS for a list in Angular 9

My task involves altering the HTML provided by a content management system for one of our applications. Specifically, I need to replace all "ul"s with <mat-icon>check_circle_outline</mat-icon> instead of the default "." The challenge lies in t ...

What is the process for incorporating a custom type into Next.js's NextApiRequest object?

I have implemented a middleware to verify JWT tokens for API requests in Next.js. The middleware is written in TypeScript, but I encountered a type error. Below is my code snippet: import { verifyJwtToken } from "../utils/verifyJwtToken.js"; imp ...