【问题标题】:CORS Angular 8 it gives meCORS Angular 8 它给了我
【发布时间】:2020-02-21 21:08:42
【问题描述】:

我的项目中存在 CORS 问题。从 Angular 8 开始:

 httpOptions = { 
      headers: new HttpHeaders({
        'Content-Type':'application/json',
        'Authorization':'Basic bm92Z*********************'
      })
    };

我确实以这种方式进行操作:

public getStudents() : Observable<IStudent[]>{
  return this.http.get<IStudent[]>(this.writeUrl, this.httpOptions)...// this.writeUrl is the request  url
}

在我的服务器中使用 java 我这样做:

public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {

    responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
    responseContext.getHeaders().add("Access-Control-Allow-Headers",
    "origin, content-type, accept, authorization");
    responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
    responseContext.getHeaders().add("Access-Control-Allow-Methods",
    "GET, POST, PUT, DELETE, OPTIONS, HEAD");

    }

它给了我 CORS,我不知道为什么,有人可以帮助我吗?

【问题讨论】:

  • 您收到的确切错误消息是什么?将其添加到您的帖子中。另外,请阅读错误消息。很有可能,该消息会告诉您究竟出了什么问题。

标签: java angular http-headers servlet-filters angular8


【解决方案1】:

Angular 服务器在 http://localhost:4200/ 上运行,Spring Boot 服务器在 http://localhost:8080/ 上运行。

将 proxy.conf.json 配置为与 package.json 并行。 proxy.conf.json 应该有

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

在 package.json 中配置相同

"scripts" :{"start": "ng serve --proxy-config proxy.conf.json"}

这个配置应该代理你对 Spring Boot 服务器的 Angular 调用。让我知道这是否适合您,如果您仍然遇到任何问题,请发布该错误。我们可以从那里检查。

【讨论】:

    猜你喜欢
    • 2020-04-12
    • 2020-10-24
    • 2020-01-23
    • 2020-07-11
    • 2020-05-23
    • 1970-01-01
    • 2020-05-29
    • 2020-09-02
    • 2020-05-06
    相关资源
    最近更新 更多