XMLHttpRequest в xxx от источника xxx был заблокирован CORS: нет заголовка «Access-Control-Allow-Origin» - PullRequest
0 голосов
/ 04 февраля 2020

привет, я работаю над пружинной загрузкой, angular 8 и mongodb. Я сталкиваюсь с ошибкой

Access to XMLHttpRequest at 'http://localhost:8080/employee/activeemployeesummary' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

, когда я тестирую тот же код на почтальоне, он прекрасно работает, однако не работает angular, и потому что chrome с использованием CORS полис.

Мой код:

package com.sani.springbootrestfulapi;
public class SpringBootMongoApplication extends SpringBootServletInitializer {
    public static void main(String args[]) {
        SpringApplication.run(SpringBootMongoApplication.class, args);
    }
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH")
                    .allowedHeaders("Origin, X-Requested-With, Content-Type, Accept")
                        .allowedOrigins("http://localhost:4200");
            }
        };
    }
}

ниже: код сотрудника контроллера

package com.sani.springbootrestfulapi.controller;
@RestController
@RequestMapping("employee")
public class EmployeeController {
    @Autowired
    private EmployeeService empService;
    @Autowired
    private OrganizationService organizationService;
    @PostMapping("/save") 
    public ResponseEntity<EmployeeEntity> save(@RequestBody EmployeeEntity emp) {
        if (empService.findByrNumber(emp.getrNumber())) 
            return new ResponseEntity<EmployeeEntity>(HttpStatus.FOUND);
        else {
            organizationService.joinOrganization(emp);
            return new ResponseEntity<EmployeeEntity>(HttpStatus.OK);
        }
    }
    @PutMapping("/update") /* here we need to pass id, the spring will consider as update */
    public ResponseEntity<EmployeeEntity> update(@RequestBody EmployeeEntity emp) {
        EmployeeEntity employee = empService.getOne(emp.getId());
        if (employee != null) {
            organizationService.joinOrganization(emp);
            return new ResponseEntity<EmployeeEntity>(HttpStatus.OK);
        } else
            return new ResponseEntity<EmployeeEntity>(HttpStatus.NOT_FOUND);
    }
    @GetMapping("/activeemployeesummary")
    public List<EmployeeEntity> getActiveEmployeeSummary() {
        List<EmployeeEntity> employee = new ArrayList<>();
        empService.getActiveEmployeeSummary().forEach(employee::add);
        return employee;
    }
    @GetMapping("/inactiveemployeesummary")
    public List<EmployeeEntity> getInactiveEmplo`enter code here`yeeSummary() {
        List<EmployeeEntity> employee = new ArrayList<>();
        empService.getInactiveEmployeeSummary().forEach(employee:`enter code here`:add);
        return employee;
    }
}

Ответы [ 2 ]

0 голосов
/ 13 февраля 2020

Добавьте это @Bean в свой @Configuration или в свой основной класс.

@Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(
            Arrays.asList("GET","POST","HEAD","DELETE","PUT","OPTIONS"));
        configuration.setMaxAge(1l);
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
0 голосов
/ 04 февраля 2020

Я думаю, вы просто пропустили этот заголовок =>

Access-Control-Allow-Origin: *
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...