使用@Crossorigin在控制器级别运行Angular的CORS问题

发布于 2025-02-05 12:28:21 字数 1228 浏览 2 评论 0原文

在呼叫到Spring Boot 2.6.4 Web Service

”在此处输入图像说明“

这是Angular 13中的代码:

let headers = new HttpHeaders({
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'Content-Type',
  'Access-Control-Allow-Methods': 'GET,POST,OPTIONS,DELETE,PUT'
});
let options = { headers: headers };

this.http.get<any>("http://localhost:8080/country/available", options).subscribe(data => {
  console.log(data);
});

我有@Crossorigin> controlter 在控制器级别:

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("country")
public final class CountryController {

    private final transient CountryService countryService;

    @Autowired
    public CountryController(final CountryService countryService) {
        this.countryService = countryService;
    }


    @GetMapping("/available")
    public List<Country> getAvailableCountries() {
        return countryService.getAvailableCountries();
    }
}

I'm getting a CORS error when running calls to the Spring Boot 2.6.4 web service

enter image description here

Here is the code in Angular 13:

let headers = new HttpHeaders({
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'Content-Type',
  'Access-Control-Allow-Methods': 'GET,POST,OPTIONS,DELETE,PUT'
});
let options = { headers: headers };

this.http.get<any>("http://localhost:8080/country/available", options).subscribe(data => {
  console.log(data);
});

I have the controller annotated with @CrossOrigin at the controller level:

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("country")
public final class CountryController {

    private final transient CountryService countryService;

    @Autowired
    public CountryController(final CountryService countryService) {
        this.countryService = countryService;
    }


    @GetMapping("/available")
    public List<Country> getAvailableCountries() {
        return countryService.getAvailableCountries();
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

執念 2025-02-12 12:28:21

尝试一下
@crossorigin(origins =“*”,washeheaders =“*”,maxage = 3600)

,或者您可以在安全配置中作为http.cros()

Try this
@CrossOrigin(origins = "*", allowedHeaders = "*" ,maxAge = 3600)

or you can do it in the security configuration as http.cros()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文