Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

java - CORS Angular 8 it gives me

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...