Nag
Nag

Reputation: 15

We have implemented proxy for Angular 8 application running on 4200 to back end api running on Tomcat 8080 is not working

We have implemented proxy for Angular 8 application running on :4200 to back end api running on Tomcat 8080. is not working

using angular version like below Angular CLI: 8.3.20 Node: 12.13.1 OS: win32 x64 Angular: 8.2.14

    let me mention changes we did.
    proxy.conf.json 
    {
      "/student/allstudent": {
        "target": "http://localhost:8080",
        "secure": false,
        "pathRewrite": {
          "^/student/allstudent": ""
        },
        "logLevel": "debug",
        "changeOrigin": true
      }
    }

    in `package.json` we added this line "start": "ng serve --proxy-config proxy.conf.json"
    In `angular.json` file we have added below proxy config under serve.
    "options": {
                "browserTarget": "PricingWorkBench-ui:build",
                "proxyConfig": "proxy.conf.json"
              },

    service method look like this in Angular 
    public getStudentDetails(): Observable<any> {
        return this.http.get("http://localhost:8083/student/allstudent").
          pipe(
            map((data: any) => {
             return data;
            })
          )
      }

Still we are getting the below error please help me.

 Access to XMLHttpRequest at 'http://localhost:8083/student/allstudent' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
    core.js:6014 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:8083/student/allstudent", ok: false, …}

Upvotes: 1

Views: 748

Answers (1)

C.OG
C.OG

Reputation: 6529

If your endpoint is on http://localhost:8083/student/allstudent.

Your proxy.conf.json should be:

{
    "/student/allstudent": {
        "target": "http://localhost:8083",
        "secure": false,
        "logLevel": "debug",
        "changeOrigin": true
    }
}

And your method will look like:

public getStudentDetails(): Observable<any> {
    return this.http.get("/student/allstudent").
        pipe(
            map((data: any) => {
                return data;
            })
        )
    }
}

Normally this route will evaluate to http://localhost:4200/student/allstudent but the proxy will take the route /student/allstudent and map it to the target listed in the proxy.conf.json which is http://localhost:8083

Upvotes: 1

Related Questions