0
votes

Okay so the problem I am having deals with using CakePhp (v3) and AngularJS. I want to use CakePhp purely to host my JSON webservices. I have this working and the routes prefixed with API. The problem I have is getting Html 5 routing to work with Angular. For instance, if I go to http://localhost/appname/home I want Angular to intercept this route not CakePhp. Currently, if I were to do this CakePhp will complain that the HomeController doesn't exist. I found this stack overflow post which allowed me to get Angular Hashtag routing functional/while maintaining the /api/* routes, but I really don't like to have my routes look like http://localhost/appname/#/home. I feel like there should be an .htaccess change I could make to allow Cake to handle the default URL path (ie: http://localhost/ thus opening by default home.ctp) but otherwise only look for http://localhost/api/* prefixed routes. I did try adding a RewriteRule ^/api/* with no luck unfortunately. I typically don't work in Apache/PHP in general so I am struggling to find the solution to this problem. Also, I made sure the rewrite module is enabled in my httpd.conf file. Here is my current routes.php file showing the API prefixing and the default routes to bring up home.ctp when hitting the root of the host. Any guidance from a more seasoned *AMP developer is much appreciated!

<?php

use Cake\Core\Plugin;
use Cake\Routing\Router;

Router::defaultRouteClass('Route');

Router::prefix('api', function ($routes) {
    $routes->extensions(['json', 'xml']);
    $routes->resources('Users');
    $routes->resources('UserInfo');
    Router::connect('/api/users/register', ['controller' => 'Users', 'action' => 'add', 'prefix' => 'api']);
    Router::connect('/api/userinfo/create', ['controller' => 'UserInfo', 'action' => 'add', 'prefix' => 'api']);
    $routes->fallbacks('InflectedRoute');
});

Router::scope('/', function ($routes) {
    $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
    $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
    $routes->fallbacks('InflectedRoute');
});

Plugin::routes();
1
Angular is not a server side technology... whatever url the browser sends to the server it will be get by your php app first. - José Lorenzo Rodríguez
Jose thank you yes I am fully aware Angular is a client side technology. I should be able to enable html 5 routing though with Cakephp ignoring all non /api/ routes. That is the crux of my issue. By enabling html5 routing on Angular I would then be able to hit routes without the default # routing mechanism, thus a cleaner URL. Make sense? - Shawn

1 Answers

1
votes

Maybe I'm misunderstanding your question, but by the time the request gets to the server, wouldn't it already be too late? If you want "angular to intercept" the route, the solution would need to be done client side and not in a .htaccess file. So you would have angular route that routes /appname/home to the correct file.