【问题标题】:XMLHttpRequest at xxx from origin xxx has been blocked by CORS: No 'Access-Control-Allow-Origin' header来自 xxx 的 xxx 处的 XMLHttpRequest 已被 CORS 阻止:没有“Access-Control-Allow-Origin”标头
【发布时间】:2020-05-20 03:31:24
【问题描述】:

您好,我正在研究 spring boot、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

当我在邮递员上测试相同的代码时,它工作得非常好,但是它不能工作,因为 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;
    }
}

【问题讨论】:

  • 由于浏览器中的同源策略限制,您只会在浏览器中发出 CORS。
  • 感谢您的回复。你能给出一个示例代码,我必须在哪里写标题 Access-Control-Allow-Origin: *
  • 您好,感谢您的回复。请在下面找到错误和标题:---GENERAL--- 请求 URL:localhost:8080/employee/activeemployeesummary 请求方法:OPTIONS 状态代码:200 远程地址:[::1]:8080 推荐人策略:no-referrer-when-降级---响应标题---允许:OPTIONS、GET、HEAD、POST 内容长度:0 日期:星期日,2020 年 2 月 9 日 07:05:28 GMT
  • --REQUEST HEADER-- Accept: / Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Access-Control- Request-Headers: access-control-allow-origin Access-Control-Request-Method: GET Connection: keep-alive Host: localhost:8080 Origin: localhost:4200 Referer: localhost:4200/employee-master Sec-Fetch-Dest: empty Sec-Fetch -模式:cors Sec-Fetch-Site:同站点用户代理:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36

标签: spring-boot cors


【解决方案1】:

将此@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;
    }

【讨论】:

  • 感谢您的及时回复,我会在试用后回复。
  • 亲爱的,我仍然遇到同样的错误:如果你愿意,我可以上传我的项目文件,如果你可以检查一下。谢谢。从源“localhost:4200”访问“localhost:8080/employee/activeemployeesummary”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源。
  • 你能更新完整的控制台截图并在你的问题中更新它吗?
  • 我更新了控制台错误截图。找到下面的链接stackoverflow.com/questions/60236921/…
  • 嗨,我确实删除了所有安全配置,并测试了我的项目,即使它给出了同样的错误,截图在上面的 cmets 中给出。所以在我的新项目中没有安全重新配置。
【解决方案2】:

我想你只是错过了那个标题 =>

Access-Control-Allow-Origin: *

【讨论】:

    猜你喜欢
    • 2022-09-27
    • 2022-12-02
    相关资源
    最近更新 更多