【问题标题】:the annotation @CrossOrigin("*") not work注释 @CrossOrigin("*") 不起作用
【发布时间】:2020-10-09 12:56:54
【问题描述】:

我遇到错误“从源 'http://localhost:4200' 访问 XMLHttpRequest 在 'http://localhost:4200' 已被 CORS 策略阻止:请求的资源上不存在 'Access-Control-Allow-Origin' 标头”而我在我的 Spring Boot 应用程序中添加了注释 @CrossOrigin("*")

@RestController
@RequestMapping("/products")
@CrossOrigin("*")
 public class ProductController {

  @Autowired
  private ProductService productService;

 @PostMapping(value = "/getPro", consumes = {"application/json"}, produces = 
    {"application/json"})
 public ResponseEntity<?> getPro(@RequestBody Product product){
    return this.productService.getPro(product);
  }

在我的前端我有:

export class ProductService {
  public productModel : Product 
  private baseUrl = 'http://localhost:8081';
  constructor(private http:HttpClient) { }
  getPro () {
  return this.http.post<Product>(this.baseUrl + "/products/getPro", 
   JSON.stringify(this.productModel));
  }
  }

谁能帮帮我?

PS:我正在使用这个应用程序,就像一个 feign 客户端我的意思是实际上我正在使用 FeignClient 调用另一个应用程序!这可能是问题吗?

【问题讨论】:

  • 你在使用 spring security 吗? + 为什么你在 spring "/getProductsData" 和 angular "/getPro" 中有?
  • @Roronoa_D._Law No
  • 好的,那么 url "/getPro" 怎么样
  • @Roronoa_D._Law 这是一个小错误!编辑了我的帖子看看
  • 失败的请求是 OPTIONS 请求吗?

标签: java angular cors


【解决方案1】:

我会建议你摆脱@crossOrigin

您可以在配置文件中执行以下操作

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");// Your allowed paths here
    }
}

我建议您仅通过使用反向代理将所有内容移至 Angular。

{
  "/api": {
    "target": "http://localhost:8081",
    "secure": false
  }
}

在此处查看 github 项目。 https://github.com/vohra01/parking-demo-SG/blob/master/IdeaProjects/parking-demo/parking-ui-app/proxy.conf.json

【讨论】:

    猜你喜欢
    • 2019-09-18
    • 2016-07-01
    • 1970-01-01
    • 2018-01-21
    • 2014-08-14
    • 1970-01-01
    • 2023-03-26
    • 2013-09-20
    • 2012-09-19
    相关资源
    最近更新 更多