CORS Angular 8 it gives me

三世轮回 提交于 2021-02-05 12:22:59

问题


I have a CORS problem in my project. From Angular 8 I do:

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

and I do get operation in this way:

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

In my server with java I do:

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");

    }

it gives me CORS and I don't know why, anyone can help me?


回答1:


Angular server runs on http://localhost:4200/ and spring boot server runs on http://localhost:8080/.

configure a proxy.conf.json parallely to package.json. proxy.conf.json should have

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

configure the same in package.json

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

This configuration should proxy your angular calls to spring boot server. Let me know if this works for you, if you still face any issue, post that error. we could check from there.



来源:https://stackoverflow.com/questions/58559787/cors-angular-8-it-gives-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!