Angular 或 Angular 6 中的跨源资源共享 (CORS)。在具有不同端口的本地主机上进行跨域调用时出现问题

Ram*_*dam 5 cross-domain cors spring-boot angular angular6

我遇到过一种情况,我从 Angular 6 应用程序调用 Spring Boot 应用程序。当我以与在不同端口上运行的应用程序的角度调用 HTTP post 方法时,它会引发异常。

从源“ http://localhost: 4200 ”访问位于“http://localhost:8080/api”的XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP好的状态。

我的 Angular 应用程序在“ http://localhost:4200 ”上运行,端口号:4200 我的 Spring Boot 应用程序在“ http://localhost:8080/api ”上运行:端口号:8080。

没有直接的答案可以解决这个问题。有一些技巧可以禁用 Chrome 中的安全性,使用 NGINX 可以解决此问题。

Ram*_*dam 5

为解决上述问题

  1. 首先,您需要共享端口 4200 的 Spring boot 资源。在要共享的资源的类或方法上使用@CrossOrigin(origins = " http://localhost:4200 ")注解。

  2. 您必须在角度应用程序中配置代理。因此,在 Angular 根应用程序中创建一个 proxy.json 文件。内容如下

    {
    "/api/*": {
        "target": "http://localhost:8080",
        "secure": "false",
        "logLevel": "debug",
        "changeOrigin": true
    }
    
    Run Code Online (Sandbox Code Playgroud)

    }

  3. 然后运行ng serve --proxy-config proxy.json这个命令它将编译代码。您应该在控制台上看到类似的内容。

    building modules 3/3 modules 0 active[HPM] Proxy created: /api -> 
    http://localhost:8080 Subscribed to http-proxy events: [ 'error', 'close' ]
    
    Run Code Online (Sandbox Code Playgroud)