【问题标题】:Use Laravel and Angularjs Routing at once同时使用 Laravel 和 Angularjs 路由
【发布时间】:2019-01-21 18:00:09
【问题描述】:

我正在开发一个电子商务 WebApp。其中我使用 Laravel 作为后端,使用 Angularjs 作为前端。但是当我点击特定的导航项时它会出现问题,但是当我重新加载页面时,它将进行 laravel 路由,并且我所有的 css、js、图像等都无法正确加载。

Laravel 代码:

Route::get('/', function () {
    return view('index');
});

Route::get('/dashboard', function () {
    return view('dashboard');
});

Route::get('/products', function () {
    return view('products');
});

Angularjs 路由:

var ecommerceApp=angular.module('ecommerceApp',['ngAnimate', 'ngSanitize', 'ui.bootstrap','ngRoute']);

ecommerceApp.config(['$routeProvider','$locationProvider',function($routeProvider,$locationProvider) {

        $locationProvider.html5Mode({
          enabled: true,
          requireBase: false
        });

        $routeProvider
        .when("/a", {
            templateUrl : "dashboard",
            controller: 'ecommerce'
        })

        .when("/products", {
            templateUrl : "products",
            controller: 'ecommerce'
        })
    }]);

Before Refresh

After Reload

我陷入了这个问题,请帮助我。 提前致谢

【问题讨论】:

标签: javascript php angularjs laravel ngroute


【解决方案1】:

您可以创建一个将所有请求发送到单个控制器操作或视图文件的路由,以便在客户端而不是服务器端完成路由。

将以下内容添加为您的路线文件中的最后一条路线。如果您需要任何服务器端路由,则它们需要在它之前。

// [Needs to be last] Catch all non-routed GET request to SpaController
Route::get('/{any}', function () {
    return view('index');
})->where('any', '.*');

这是使用正则表达式基本上将所有内容发送到单个操作。见:https://laravel.com/docs/5.4/routing#parameters-regular-expression-constraints

【讨论】:

  • 问题依旧
【解决方案2】:

如何:配置您的服务器以使用 html5Mode1

启用 html5Mode 后,您的网址中将不再使用 # 字符。 # 符号很有用,因为它不需要服务器端配置。如果没有#,url 看起来会更好,但它也需要服务器端重写。这是一个例子:

Apache 重写

<VirtualHost *:80>
    ServerName my-app

    DocumentRoot /path/to/app

    <Directory /path/to/app>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html to allow html5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>

【讨论】:

  • 如果需要我可以发送源代码,如果你能解决这个问题?
【解决方案3】:

我找到了解决方案,现在当我使用 $stateProvider 而不是 $locationProvider 它工作正常。

//Angularjs代码

ecommerceApp.config(['$stateProvider','$urlRouterProvider',function($stateProvider, $urlRouterProvider) {
	
  $stateProvider
	.state('products', {
      url: '/products',
      templateUrl: '/products',
      controller: 'ecommerce'
    })
	.state('product/add', {
      url: '/product/add',
      templateUrl: '/product/add',
      controller: 'ecommerce'
    });
 }]);
<li class=""><a ui-sref="products"><i class="fas fa-tags"></i>Product</a></li>



<div data-ui-view=""></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-08
    • 2014-07-28
    • 2017-06-11
    • 2013-05-10
    • 2016-11-15
    • 2018-05-17
    • 2014-02-28
    • 2020-05-04
    相关资源
    最近更新 更多