【问题标题】:How to enable CORS in Spring Boot and Angular如何在 Spring Boot 和 Angular 中启用 CORS
【发布时间】:2020-09-13 03:05:47
【问题描述】:

我在我的 Spring Boot 服务器中启用了 CORS,如下所示。

@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/api/v1")
public class EmployeeController {
    @Autowired
    private EmployeeRepository employeeRepository;

    @PostMapping("/employees")
    public Employee createEmployee(@Valid @RequestBody Employee employee) {
        return employeeRepository.save(employee);
    }
}

创建新员工时,我收到错误,

Access to XMLHttpRequest at 'http://localhost:8080/springboot-crud-rest/api/v1/employees' 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.

我还尝试在已弹出的 Angular CLI 应用程序上启用服务器端代理,但我找不到任何文件作为 webpack.config.js

【问题讨论】:

  • 下面更新了答案。请检查。

标签: angular spring spring-boot api cors


【解决方案1】:

在 CORS 更改中,前端不需要更改。后端必须正确配置它,如果您将此后端部署在云上,则需要进行一些设置。否则你应该对你所做的方法没问题

只需将相同的 CrossOrigin 放在 @PostMapping 上,如下所示。应该没问题。

@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/api/v1")
public class EmployeeController {
    @Autowired
    private EmployeeRepository employeeRepository;

    @CrossOrigin(origins = "http://localhost:4200")
    @PostMapping("/employees")
    public Employee createEmployee(@Valid @RequestBody Employee employee) {
        return employeeRepository.save(employee);
    }
}

顺便说一句,在每个 api 上使用此注释并不是最佳做法。而是在您的 application.properties 中配置它,使其适用于所有 API。

【讨论】:

  • 如何将 application.properties 放入全局启用它?我已经尝试了多种配置,但似乎都不起作用
猜你喜欢
  • 2020-05-29
  • 2021-04-03
  • 2019-01-14
  • 2018-08-02
  • 2019-10-10
  • 2019-11-17
  • 2021-03-01
  • 2019-07-31
  • 2016-12-04
相关资源
最近更新 更多