Mhmd Backer Shehadi
Mhmd Backer Shehadi

Reputation: 589

Angular 6 call localhost API

I am trying to call an API locally in my angular 6 app, the API URL is http://localhost/myapi I added a proxy config file that point to this URL but I got 404 error when I run my app.

My proxy.config.json file:

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

package.json file:

"serve-dev": "ng serve --source-map=false --proxy-config proxy.config.json",

http.service.ts file:

export class HttpService{
     static serverApiUrl : string  = "/api/"
}

auth.service.ts file :

 this.http.get(HttpService.serverApiUrl+"site/check-auth")
            .map(response => {
                if(response['auth'] == 1) {
          return true;
                } else {
          this.router.navigate(['/auth'])
                    return false;
                }
            });

In the console I got this:

http://localhost:4200/api/site/check-auth 

any suggestions.

Upvotes: 4

Views: 11507

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93083

It looks like you need to rewrite the URL path, using something like this:

{
    "/api": {
        "target": "http://localhost",
        "secure": false,
        "logLevel": "debug",
        "pathRewrite": {
            "^/api": "/myapi"
        }
    }
}

I've removed /* from the prefix you had and added a pathRewrite section. I believe what you had before was attempting to proxy to localhost/myapi/api/site/check-auth (with that extra /api), which should be stripped with the pathRewrite section.

Upvotes: 2

Related Questions