Проблема политики CORS при обращении к службе отдыха (Spring Boot) из приложения Angular5 - PullRequest
0 голосов
/ 20 ноября 2018

Я получаю сообщение об ошибке ниже, когда я пытаюсь запустить почтовый сервис из Angular 5

Не удалось загрузить ресурс: сервер ответил с состоянием 403 (Запрещено) Доступ к XMLHttpRequest на 'https://xxxx/xxxx/services/exportVarianceHome' из источника 'http://localhost:4200' было заблокировано политикой CORS:

Ответ на запрос предварительной проверки не проходит проверку контроля доступа: заголовок «Access-Control-Allow-Origin» отсутствуетприсутствует на запрошенном ресурсе.

Ниже представлена ​​моя конфигурация перехватчика в Angular 5

import { Injectable, NgModule} from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse} from '@angular/common/http';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import 'rxjs/add/operator/do';
@Injectable()
export class HttpsRequestInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const dupReq = req.clone({ headers: req.headers
    .set('Access-Control-Allow-Origin','*')
    .set('Content-Type', 'application/json')
    .set('Authorization', 'Basic XXXXXXXXXXXXXXXXXXXXXX')
    .set('Access-Control-Allow-Credentials','true') });
    return next.handle(dupReq);
  }
};
@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: HttpsRequestInterceptor, multi: true }
  ]
})

И Angular Post Call

import { HttpClient} from '@angular/common/http';
constructor(private httpClient:HttpClient){
         getLookupDetails();
}

  getLookupDetails(){
    this.httpClient.get(this.servicsUrl).subscribe(
          (data:any) => {
            console.log("JSON Response " + JSON.stringify(data));
          }
        )
     }

И настройка перекрестного источникана стороне сервера (SpringBoot)

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication(scanBasePackages = {"com.controller.gtm"})
public class BrokerValidationApplication extends SpringBootServletInitializer implements WebMvcConfigurer  {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(BrokerValidationApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(BrokerValidationApplication.class, args);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        System.out.println(">=== Inside Cors Orgin Mapping addCorsMappings ===>");
        registry.addMapping("/services/**")
          .allowedOrigins("*")
          .allowedMethods("POST", "GET",  "PUT", "OPTIONS", "DELETE")
          .allowedHeaders("*")
          .allowCredentials(true)
          .maxAge(4800);
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...