user2094257
user2094257

Reputation: 1715

Angular-cli: issues setting up the proxy to handle complex requests going to another domain

I am busy with a web app that needs to make http requests to a server on my local network. i'm using Angular-cli to build/run my project. When makeing any complex requests i'm running into CORS issues and trying to use the angular-cli proxy to handle those complex requests... I set it up exactly as it's done on the angular-cli github page but it doesn't seem to work. Any idea what i'm doing wrong?

my code:

proxy.conf.json:

{
"/api":{
"target":"http://10.60.160.34/BRMServices/WebEnquiry/",
"secure":false
}
}

from package.json:

"start": "ng serve --proxy-config proxy.conf.json",

a function with a complex request that's supposed to go to the proxy:

postStockTake(stockTakeModel: StockTakeModel) : Observable<Response> {    
  return this.http.post("/api" + "/StockTake/AddToStockTake", JSON.stringify(stockTakeModel), {headers: this.headers})
        .map((res: Response) => res.json())
        .catch((error: any) => Observable.throw(error.json().error || 'server error'));
  }

I then run the app with npm start instead of ng serve... When it starts to build I see the following in my command prompt console:

> [email protected] start C:\Users\User1\Documents\trade-link\barcode-checker
> ng serve --proxy-config proxy.conf.json

And in my chrome dev tools console I see:

zone.js:1725
POST
http://localhost:4200/api/StockTake/AddToStockTake
405 (Method Not Allowed)

So it's clearly still trying to post to localhost even though I added the local server's IP address in the target value of the proxy.conf file?

Upvotes: 2

Views: 3283

Answers (1)

VadimB
VadimB

Reputation: 5711

I had similar problem before and I found out that proxy map path not as was expected.

When I have config:

{
  "/api":{
  "target":"http://10.60.160.34/BRMServices/WebEnquiry/",
  "secure":false
}

I expect all requests to api/<sub-path> path will be mapped to http://10.60.160.34/BRMServices/WebEnquiry/<sub-path>, but it's incorrect.

Your virtual path api/<sub-path> will be mapped to:

http://10.60.160.34/BRMServices/WebEnquiry/api/<sub-path>

So I got incorrect url I and my server throwing similar error. Solution for was to remove incorrect api subpath from my destination url using next configuration option

{
  "/api": {
    "target": "http://10.60.160.34/BRMServices/WebEnquiry/",
    "secure": false,
    "pathRewrite": {"^/api" : ""}
  }
}

I had similar question but did not receive answer so found solution for my problem themself.

Redirect Angular2 http requests through proxy

Hope this helps.

Upvotes: 6

Related Questions