如何避免 Angular 和 Spring 引导项目中的 CORS 问题?

How to avoid the problem of CORS in Angular and Spring boot project?

我实际上创建了一个 angular 服务以从 运行 在 'localhost:8080/'(端点/用户)上的服务器获取数据。 但是当我在 'localhost:4200' 上为 angular 项目提供服务时,它出现了这个错误:从原点访问 'localhost:8080/user' 处的 XMLHttpRequest ..

我试图通过在控制器中添加@CrossOrigin(origins = "*") 来解决这个问题 我在 angular 项目中添加了一个 proxy.conf.json 就像我在这里找到的:'https://angular.io/guide/build' 但问题仍然存在。

这是 angular 服务:

  @Injectable({
  providedIn: 'root'
})
export class RestService {
  api = 'localhost:8080/user'
  constructor(private http: HttpClient) { }
  getUsers(): Observable<String> {
    return this.http.get<String>(this.api);
  }
}

这是我的 proxy.conf.json :

{
    "/*": {
        "target": "http://localhost:8080",
        "secure": false,
        "logLevel": "debug"
    }
}

这是 angular.json 中的配置文件:

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "crud:build",
            "proxyConfig": "src/proxy.conf.json"
          }

这是 spring 引导控制器:

@RestController
@CrossOrigin(origins = "*")

public class userController {
    @GetMapping("/user")
    public String getuser(){
        return "the user name is bilel" ;
    }
}

你不想告诉你的 Angular 服务关于目标服务器和它的端口,它反对使用代理 conf。

调用类似于通用 api/ 根端点的东西并映射它:

export class RestService {
  api = '/api/user'
  constructor(private http: HttpClient) { }
  getUsers(): Observable<String> {
    return this.http.get<String>(this.api);
  }
}

还有这样的代理:

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

要构建@Alain Boudard 的答案,您需要添加路径重写:

export class RestService {
  baseUrl = 'api/user'

  constructor(private http: HttpClient) { }

  getUsers(): Observable<string> {
    return this.http.get<string>(this.baseUrl);
  }
}

和 proxy.conf.json 文件中,不要忘记重写路径,以便在调用后端之前从 URL 中删除 'api':

{
  "/api/*": {
    "target": "http://localhost:8080",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true,
    "pathRewrite": {
      "^/api": ""
    }
  }
}

PS:顺便说一句,您很少需要使用字符串类型,而是使用原始字符串(小写 s):https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html