Laravel 4 as RESTful backend for AngularJS

前端 未结 2 1690
北荒
北荒 2021-01-30 07:51

I am trying to build a web application which should use Laravel as a RESTful backend API and AngularJS on client side. I read all the other post on Stackoverflow about the issue

2条回答
  •  迷失自我
    2021-01-30 08:03

    Finally I found a working solution, perfect in my scenario, which does not require a subdomain. In this case Laravel acts exclusively as a RESTful web service, no server side views or templates: the presentation layer is completely demanded to AngularJS.

    Let's say I have two completely decoupled applications (FE e WS) inside the same root folder:

    root
    |__fe
    |__ws
    

    I modified virtual host settings under Apache httpd-vhosts.conf file the following way:

    
        ServerName myapp.com
        DocumentRoot "\www\root\fe"
    
        alias /ws "\www\root\ws\public"
        
            Options Indexes FollowSymLinks MultiViews
            AllowOverride all
                Order allow,deny
            Allow from all
        
    
    

    I then added "RewriteBase /ws" into my laravel/public/.htacces file:

    
        Options -MultiViews
        RewriteEngine On
    
        RewriteBase /ws
    
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.php [NC,L]
    
    

    This way I can write in the browser (for instance):

    http://myapp.com             (AngularJS client side root)
    http://myapp.com/ws/users    (RESTful service endpoint for "users")
    

    And then define a client side, AngularJS routing the following way:

    app.config(function($routeProvider) {
        $routeProvider
            .when('/', {controller: 'HomeController', templateUrl: 'templates/home.html'})
            .when('/users', {controller: 'UsersController', templateUrl: 'templates/users.html'})
            .otherwise({redirectTo: '/'});
    });
    

    Linking it to a RESTful resource this way:

    app.factory('User', function($resource) {
        return $resource('http://myapp.com/ws/users');
    });
    
    app.controller('UsersController', function($scope, User) {
        $scope.title = "Users";
        $scope.users = User.query();
    });
    

    I enabled HTML5 history API, adding this line to configure my Angular application:

    $locationProvider.html5Mode(true);
    

    together with (inside index.html head section):

    
    
    

    So the last requirement to solve problems like browser page refresh, deep linking, or direct page bookmark, is to add a .htaccess file in the root of the folder which contains the Angular application:

    
        Options -MultiViews
        RewriteEngine On
    
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.html [NC,L]
    
    

    Hope it helps!

提交回复
热议问题