Laravel 4 作为 AngularJS 的 RESTful 后端

2024-02-24

我正在尝试构建一个 Web 应用程序,该应用程序应使用 Laravel 作为 RESTful 后端 API,并在客户端使用 AngularJS。 我阅读了 Stackoverflow 上有关该问题的所有其他帖子,但没有人明确回答我的疑问,至少我没有找到明确的源示例。

例如...

我是否应该开发两个完全不同的应用程序,一个使用 Laravel 的后端应用程序,另一个使用 AngularJS 的纯客户端应用程序? 但在这种情况下:如何通过单个域(或虚拟主机)来处理它们?

或者我应该在 Laravel 中的“views”文件夹中创建 AngularJS 模板,并从中调用 Laravel 服务?我怀疑这是最好的方法:在这种情况下,后端并未与前端实现完全解耦。

另外,如何正确处理路由?我的意思是:我想从 AngularJS 路由(例如菜单/页面导航)进行管理,仅调用 Laravel 来检索数据并填充我的视图。 按照本文中的建议移动“public”文件夹(Angular JS + Laravel 4:如何编译生产模式? https://stackoverflow.com/questions/19089244/angular-js-laravel-4-how-to-compile-for-production-mode)可能有帮助吗?

预先感谢您的建议、示例...


最后,我找到了一个工作解决方案,非常适合我的场景,不需要子域。 在这种情况下,Laravel 专门充当 RESTful Web 服务,没有服务器端视图或模板:表示层完全需要 AngularJS。

假设我在同一个根文件夹中有两个完全解耦的应用程序(FE e WS):

root
|__fe
|__ws

我按以下方式修改了 Apache httpd-vhosts.conf 文件下的虚拟主机设置:

<VirtualHost *:80>
    ServerName myapp.com
    DocumentRoot "\www\root\fe"

    alias /ws "\www\root\ws\public"
    <Directory "\www\root\ws\public">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all
            Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

然后我将“RewriteBase /ws”添加到我的 laravel/public/.htaccess 文件中:

<IfModule mod_rewrite.c>
    Options -MultiViews
    RewriteEngine On

    RewriteBase /ws

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [NC,L]
</IfModule>

这样我就可以在浏览器中编写(例如):

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

然后定义一个客户端,AngularJS 路由如下:

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

通过这种方式将其链接到 RESTful 资源:

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();
});

我启用了 HTML5 历史 API,添加此行来配置我的 Angular 应用程序:

$locationProvider.html5Mode(true);

连同(在index.html head部分内):

<base href="/" />
<meta name="fragment" content="!" />

因此,解决浏览器页面刷新、深层链接或直接页面书签等问题的最后一个要求是在包含 Angular 应用程序的文件夹的根目录中添加一个 .htaccess 文件:

<IfModule mod_rewrite.c>
    Options -MultiViews
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.html [NC,L]
</IfModule>

希望能帮助到你!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel 4 作为 AngularJS 的 RESTful 后端 的相关文章

随机推荐