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:

view plain print about

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:

view plain print about
2 context: [
3 "/php"
4 ],
5 target: "",
6 pathRewrite: {
7 "^/php/": ""
8 },
9 changeOrigin: true
10 }

So, the Angular code tries to hit:

view plain print about

And the Proxy knows to convert that to:

view plain print about

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:

view plain print about
1pathRewrite: function (path, req) {
2 return path.replace('/php/', '') + '/'

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!