The Same Origin Policy has prevented access to the remote resource located at http://localhost:8082/api/countries due to a Cross-Origin Request Block

Solution

The XMLHttpRequest access to 'http://localhost:8082/api/countries' from the origin 'http://localhost:4200' has been blocked by the CORS policy. The response to the preflight request is failing the access control check because there is no 'Access-Control-Allow-Origin' header present on the requested resource.
checkout.component.ts:153     GET http://localhost:8082/api/countries net::ERR_FAILED

I have configured the server side using spring-boot :

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setAllowedOrigins(Arrays.asList(allowOrigin));
        corsConfiguration.setAllowedHeaders(Arrays.asList("Origin", "Access-Control-Allow-Origin", "Content-Type",
                "Accept", "Authorization", "Origin, Accept", "X-Requested-With",
                "Access-Control-Request-Method", "Access-Control-Request-Headers"));
        corsConfiguration.setExposedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Authorization",
                "Access-Control-Allow-Origin", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials"));
        corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

where allowOrigin: http://localhost:4200

using REST API in pom.xml:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>

My country code:

package com.kaushik.bookstore.repository;

import com.kaushik.bookstore.entity.Country;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.web.bind.annotation.CrossOrigin;

@RepositoryRestResource
@CrossOrigin
@SecurityRequirement(name = "Bearer Authentication")
@Tag(
        name = "Country",
        description = "Here, GET all details of countries endpoint."
)
public interface CountryRepository extends JpaRepository<Country, Integer> {
}

Adding Rest App config:

package com.kaushik.bookstore.config;

import com.kaushik.bookstore.entity.Country;
import com.kaushik.bookstore.entity.Product;
import com.kaushik.bookstore.entity.ProductCategory;
import com.kaushik.bookstore.entity.State;
import jakarta.persistence.EntityManager;
import jakarta.persistence.metamodel.EntityType;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotationValue;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.CorsRegistry;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Configuration
@AllArgsConstructor
public class RestAppConfig implements RepositoryRestConfigurer {

    private final EntityManager entityManager;

    @Value("${allowed-origins}")
    private String[] allowOrigin;

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) {
        HttpMethod[] theUnsupportedActions = {HttpMethod.POST, HttpMethod.PUT,HttpMethod.PATCH, HttpMethod.DELETE};
        disableHttpsMethods(Product.class, config, theUnsupportedActions);
        disableHttpsMethods(ProductCategory.class, config, theUnsupportedActions);
        disableHttpsMethods(Country.class, config, theUnsupportedActions);
        disableHttpsMethods(State.class, config, theUnsupportedActions);
        exposeIds(config);
        cors.addMapping("/**")
                .allowedHeaders("*")
                .allowedOrigins(allowOrigin);
    }
}

In Angular 15, I am using:

ngOnInit(): void {
     this.formService.getCountries().subscribe((data) => {
      this.countries = data;
    });
}

In Form service:**http://localhost:8082/api/countries **

export class FormService {
  private countriesUrl = 'http://localhost:8082/api' + '/countries';
  
  constructor(private httpClient: HttpClient) {}

  getCountries(): Observable<Country[]> {
    return this.httpClient
      .get<GetResponseCountries>(this.countriesUrl)
      .pipe(map((response) => response.countries));
  }
}

In Interceptor:

import {
  HttpEvent,
  HttpHandler,
  HttpHeaders,
  HttpInterceptor,
  HttpRequest,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { exhaustMap, Observable, take } from 'rxjs';
import { AuthService } from './auth.service';

@Injectable()
export class AuthInterceptorService implements HttpInterceptor {
  constructor(private authService: AuthService) {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return this.authService.user.pipe(
      take(1),
      exhaustMap((user) => {
        if (!user) {
          return next.handle(req);
        }
        let tokenStr = `Bearer ${user?.token}`;
        const modifyReq = req.clone({
          headers: new HttpHeaders()
            .set('Authorization', tokenStr)
            .set('Content-Type', 'application/json'),
        });
        return next.handle(modifyReq);
      })
    );
  }
}

Resolved Issue: Implementing CORS policy correctly and configuring server-side settings resolved the CORS error.

Answer №1

Here are some suggestions for troubleshooting:

  1. Consider removing @CrossOrigin from the CountryRepository class if you have already set a global CORS policy in the RestAppConfig.
  2. Verify that the allowOrigin value in the RestAppConfig is 'http://localhost:4200' as needed.
  3. You may want to explore an alternative method of configuring your filter in the RestAppConfig:
cors.addMapping("/**")
    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
    .allowedHeaders("*")
    .allowedOrigins(allowOrigin)
    .allowCredentials(true);
  1. Ensure that @Value("${allowed-origins}") correctly fetches its value from the properties file!

Lastly, consider clearing your browser cache as outdated CORS policies could cause issues

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

Strategies for transferring ngModel data from child components to parent components (child to parent to grandparent)

I am currently working on multiple parent components that utilize template-driven forms: user-data.components.ts admin-data.components.ts customer-data.components.ts Each of these parent components have form elements that are child components utilizing NG ...

The attribute 'custom' is not a recognized property on the type 'EventEmitter<any>'

Currently utilizing ionic 3, I have a part component alongside a parts page. Parts.html page: <ion-row> <part [part]="part"></part> </ion-row> The json structure for the part variable in parts.html is as follows: https://i.s ...

Having trouble closing my toggle and experiencing issues with the transition not functioning properly

Within my Next.js project, I have successfully implemented a custom hook and component. The functionality works smoothly as each section opens independently without interfering with others, which is great. However, there are two issues that I am facing. Fi ...

Utilizing TypeScript Generics for Creating Arrays of Objects with Inherited Type Definitions

I'm exploring the concept of type inheritance for an array of objects, where one object's value types should inherit from another. While I'm unsure if this is achievable, it's definitely worth a try. Currently, I believe my best approac ...

There seems to be an issue with the 'clr-icon' element; it is not recognized as a valid element

When I run this specific command: ng build --prod --base-href ./ An error message is displayed: ERROR in : 'clr-icon' is not a known element: 1. If 'clr-icon' is an Angular component, then verify that it is part of this module. 2. If ...

Unable to make an AJAX call to a Spring controller

I am currently attempting to make an ajax call to a Spring controller, but I am encountering an Error 405 stating "Request method 'POST' not supported." I have included my code below and would appreciate any suggestions on how to resolve this iss ...

Issue: Error encountered while trying to use the removeAttribute() function in Selenium and Java: missing closing parenthesis after argument list

WebElement removeReadOnly=driver.findElement(By.xpath("//input[@id='mat-input-0']")); js.executeScript("document.getElementBypath('//input[@id='mat-input-0']').removeAttribute('readonly');",&quo ...

Exploring the power of Vue3 with reactive nested objects and the inclusion of

It seems like I've encountered a bit of a challenge... Perhaps a bug in Vue3 with Typescript and the composition API, or maybe I'm missing something. I'm facing an issue where I'm not getting any intellisense in my IDE (Webstorm) when ...

Return a 404 status code in Angular 5

I'm facing a frustrating issue that is causing me trouble. For some reason, I can't get the 404 status to work with Angular 5. Here are the steps I've taken: In my server.ts file, I included const { AppServerModuleNgFactory, LAZY_MODUL ...

Having trouble with canceling the "Authentication Pop up" using Robot Class

Update: While previous discussions revolved around passing credentials and logging in for Authentication pop ups, this question focuses on how to cancel the Authentication popup using the Robot class. Is it even possible? /Update I have attempted to use t ...

Choosing custom element children once they're connected to the DOM: A guide

My goal is to retrieve the value of transaction-name__inputbox when the user clicks on the transaction-add__button. The function transactionAddHandler is triggered upon clicking the button. However, my attempt to select this element using document.querySe ...

Waiting for Angular to finish multiple HTTP requests

I am encountering a similar issue to the one described in this post: Angular wait for multiple http requests to complete and then fire the last one My goal is to accomplish exactly what is shown below: forkJoin( this.data.getCodes('medical'), ...

Is it necessary to include a module in another module if it is not utilized in the template?

Is it necessary to import Module2 into Module1 if a component from Module2 is being used in Module1, but only in the typescript and not the template? For instance, as a @ContentChild(Component2) component2 like shown below (Note: both modules are secondary ...

Tips for effectively modifying the color of a mat-icon using Angular

After thoroughly reviewing the documentation, I attempted to modify the color of a mat-icon using the following code snippet: <mat-icon class="white" color="primary" svgIcon="back"></mat-icon><span class="backText">back</span> Thi ...

What distinguishes ES6 from ES2015 in the TypeScript compiler option `--libs`?

Can you explain the distinction between ES6 and ES2015 in the TypeScript compiler option here? Also, what does --libs do? ...

Halt the present thread upon mutual exclusion detection

Within my android Application, I have a specific method in one of my MODEL classes that is always called from a thread separate from the UI thread. The AlarmManager runs this method periodically, and users also have the option to trigger this method from ...

Troubleshooting Node Server Startup Problems in AngularJS 2

I've been working on an Angular 2 sample app that was functioning perfectly until recently. However, when I attempt to run it now, a particular error pops up in the terminal: app/idea.ts(3,8): error TS2304: Cannot find name 'date'. The con ...

Angular: avoid API errors from being displayed in the HTML template

While working with HTTP requests in my Angular app, I encountered an issue where a status code of 400 is returned for invalid data input, causing the HTML template not to be displayed on the view. Currently, I am handling this situation by: this.myServic ...

Angular 6 Integration: Configuring CORS and JWT in Spring Boot

While working on my Spring Boot app with JWT, I encountered a CORS error when attempting to login from the Angular 6 client. Access to XMLHttpRequest at 'http://localhost:8082/login' from origin 'http://localhost:4200' has been blocked ...

Unable to render React component after updating its state

After successfully retrieving data from my API, React is failing to render the cards. export default function Subjects() { const userApi = useUserService(); const auth = useRecoilValue(AuthAtom); const [loading, setLoading] = React.useState<boolea ...