Last week I wrote about an issue I was having with PHP requiring a trailing slash in my REST Service, or else a redirect would lost the request method. Unsurprisingly, this trailing slash was causing issues with my Angular code.
My Angular code, which is shared between multiple server technologies was making calls like this:
That environment variable would change depending on the configuration loaded for the local dev server. It might be PHP, Java, ColdFusion, or NodeJS. Then my proxy would transform those values, sort of like this:
2 context: [
3 "/php"
4 ],
5 target: "http://localphp.angular.learn-with.com:8080/",
6 pathRewrite: {
7 "^/php/": "http://localphp.angular.learn-with.com:8080/A12/chapter2/php/com/dotComIt/learnWith/api/"
8 },
9 changeOrigin: true
10 }
So, the Angular code tries to hit:
And the Proxy knows to convert that to:
The problem is the trailing slash was not being added. And every tech worked fine without it until I got to PHP.
How do I add that trailing slash back in as part of the rewrite rules? It turns out you can use a custom function:
2 return path.replace('/php/', 'http://localphp.angular.learn-with.com:8080/A12/chapter2/php/com/dotComIt/learnWith/api/') + '/'
3}
I believe the traditional rewrite rules use some type of regex. But, writing a function gives us complete control. And it was easy for me to perform a replace and then add the slash back in.
If I weren't sharing code between multiple systems, I would have just added the slash as part of my Angular service. This works instead!