java - 注释 @CrossOrigin ("*") 不起作用

标签 java angular cors

我遇到错误“从来源‘http://localhost:8081/products/getPro’访问位于‘http://localhost:4200’的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在‘Access-Control-Allow-Origin’ header ”,而我在我的 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 :我正在像假客户端一样使用这个应用程序我的意思是实际上我正在调用另一个带有 FeignClient 的应用程序!这可能是问题所在?

最佳答案

我会建议你去掉 @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

关于java - 注释 @CrossOrigin ("*") 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62467413/

相关文章:

java - 字节流问题

java - 使用日期参数时,Spring Data JPA 日期 "between"查询问题

angular - graphql-tag 的 Webpack 加载器未在 Angular 8 中加载

forms - Angular 2 响应式(Reactive)详细验证

angular - 当模式对话框被关闭时,在 ionic 中调用哪个生命周期方法

javascript - React JS - 请求的资源上不存在 'Access-Control-Allow-Origin' header 。跨源资源错误

javascript - POSTMAN 工作时出现 Angular POST 交叉原点错误

javascript - NodeJS - CORS 中间件 `origin` 未定义

java - 如何防止在 soap webservice 客户端中生成 xml 'nil' 元素?

java - FTPClient - 以流方式将 Noop 发送到 FTP 服务器