July 27, 2016
Ionic 2 Proxy while Development with Gulp
From time to time you may need to add a proxy to your Ionic 2 project. It is actually really simple but many articles in the web still refer to the old Ionic 2 build using webpack. Since it is now gulp based and modularized you must use the ionic.config.json file in order to create a new proxy listening on your apps port (pbl. 8100).
1 2 3 4 5 6 7 8 9 10 11 12 |
{ "name": "client", "app_id": "", "v2": true, "typescript": true, "proxies": [ { "path": "/api", "proxyUrl": "http://someRemoteApi.com/api/v2" } ] } |
Thats it!
If you still experience troubles: Try to verify that your proxy works. This can be achieved by installing the handy npm module http-server. Then set up a server on a different port, call the proxy URL in chrome and see if the request is shown in the logs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# install http server npm i -g http-server # run http server http-server -p 9988 # in another terminal, make sure ionic runs ionic serve # then go to chrome # and call the ionic localhost URL + the proxies.path from ionic.config.json # -> e.g.localhost:8100/api # Now take a look at your http-server console: # can@xmg:~ $ http-server -p 9988 # Starting up http-server, serving ./ # Available on: # http://127.0.0.1:9988 # http://192.168.1.150:9988 # http://192.168.1.199:9988 # Hit CTRL-C to stop the server # [Wed Jul 27 2016 09:06:43 GMT+0200 (CEST)] "GET /api/v2/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/51.0.2704.79 Chrome/51.0.2704.79 Safari/537.36" # [Wed Jul 27 2016 09:06:43 GMT+0200 (CEST)] "GET /api/v2/" Error (404): "Not found" |
As we can see in the last two lines, the request has gotten trough – proxy definitely works!
Hi,
I do exactly that and this is not working for me.
I create a clean project with ionic2 beta.11 and proxy seems to not work!
Hello Michael,
have you checked with the http-server method i mentioned in the article? If yes, please upload the project to GitHub and share the link in order to receive support. 🙂
Does this only work for brwser or android app should also work?
it should be “http://someRemoteApi.com/api/v2” instead of “http://someRemoteApi.com/api/v2/”.
Hi Can,
When I do “proxies”: [
{
“path”: “/api/myapp”,
“proxyUrl”: “http://localhost:13101/”,
“rejectUnauthorized”: false
} ]
and do http.get(“/api/myapp/template”);
It is not working. But, if I do
“proxies”: [
{
“path”: “/api/myapp/template”,
“proxyUrl”: “http://localhost:13101/api/myapp/template”,
“rejectUnauthorized”: false
} ]
it is working.
What am I doing wrong ? my requirement is to map multiple apis like below
path: “api/myapp/template”
path: “”api/myapp/template/save”
path: “”api/myapp/template/{dynamic variable here}”
Thanks in advance!!