0

I have proxy.conf.json

{
"/api/*": {
    "target": "https://api.dev.xyz.com",
    "secure": false,
    "changeOrigin": true,
    "pathRewrite": { "^/api": "" },
    "logLevel": "debug"
  }
}

and I have ng serve --proxy-config proxy.conf.json in package.json file. When I run my project with npm start it showing error

ng serve --proxy-config proxy.conf.json
Browserslist: caniuse-lite is outdated. Please run next command `npm update`
10% building 3/3 modules 0 active[HPM] Proxy created: /api  ->  https://api.dev.xyz.com
[HPM] Proxy rewrite rule created: "^/api" ~> ""
[HPM] Subscribed to http-proxy events:  [ 'error', 'close' ]

I have checked multiple stack-overflow answers reference link, but still I have been stuck here from long time.

change need
  • 137
  • 2
  • 6
  • 23
  • 1
    Where do you see an error? Except for the caniuse-lite package, there is no error. It's telling you that the rewrite rule has been applied (meaning when you make an http request like `http.get('/api/something')` it will replace `/api/something` with `https://api.dev.xyz.com/something`. – Askirkela Nov 14 '19 at 08:13
  • Where exactly is the error? – Dino Nov 14 '19 at 08:13
  • I have API call like `https://api.dev.xyz.com/api/login` when I try to hit still it is showing `blocked by cors error in the browser console`. – change need Nov 14 '19 at 08:26
  • How do you create the request? Is it `this.http.get('https://api.dev.xyz.com/api/login')` or `this.http.get('/api/login')` (or even `this.http.get('/api/api/login')`, given the path rewrite in your proxy file)? – Askirkela Nov 14 '19 at 08:42
  • I'm creating request as `this.http.get('https://api.dev.xyz.com/api/login')` – change need Nov 14 '19 at 08:47

1 Answers1

0

Ok. After asking for more information (see the comments on the question), here's an answer:

What the proxy file is doing is creating a rewrite rule. That means whereever you create a request to /api/something/, it will be rewrote as https://api.dev.xyz.com/something and be somewhat considered as coming from the full url (hence no CORS errors).

Try requesting with this.http.get('/api/something') and you'll see in the console a message telling you that the request got rewritten.

Askirkela
  • 1,120
  • 10
  • 20
  • If I change request url from `https://api.dev.xyz.com/something` to `/api/something`. it is hitting http://localhost:4200/api/something instead of `https://api.dev.xyz.com/api/something` – change need Nov 14 '19 at 09:20
  • even in the angular cli it showing Rewriting path from `"/api/students?page=1&page_size=20&paginate=true" to "/students?page=1&page_size=20&paginate=true"`. – change need Nov 14 '19 at 09:30
  • and `GET /api/students?page=1&page_size=20&paginate=true ~> https://api.dev.xyz.com` – change need Nov 14 '19 at 09:30