【问题标题】:AngularJS routing in html5mode errorhtml5mode中的AngularJS路由错误
【发布时间】:2015-02-25 19:19:56
【问题描述】:

这是我的前端 AngularJS 路由:

$urlRouterProvider.otherwise('/');
$locationProvider.html5Mode(true).hashPrefix('!');
$stateProvider
.state('main', {
    url: '/',
    templateUrl: '/views/main.html',
    controller: 'MainCtrl'
})

.state('review', {
    url: '/review',
    templateUrl: '/views/review.html',
    controller: 'NewReviewCtrl'
})

.state('model', {
    url: '/:make/:model',
    templateUrl: '/views/model.html',
    controller: 'ModelPageCtrl'
});

这是我的服务器端路由(node.js):

//...some routes

app.use('/*', function(req, res){
    res.sendFile(config.rootPath + '/public/index.html');
});

使用/review 路由,一切正常,但不适用于/:make/:model

HTML:

<a href="" ui-sref="model({make: 'lenovo', model: 'thinkpad-t430'})">See more details...</a>

如果我通过该链接访问此页面,一切正常,但如果我刷新或直接访问localhost:3030/lenovo/thinkpad-t430,则会收到此错误:

Uncaught Error: [$injector:modulerr] Failed to instantiate module app to:
Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.  

可能是因为html5mode。而且我建议它不使用此 URL,因为它是一个 2 级 URL。

我该如何解决这个问题?

编辑:Express.js 配置:

app.set('view engine', 'ejs');
app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
});
app.use(bodyParser());
app.use(session({secret:"some_secret"}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(config.rootPath+"/public"));

【问题讨论】:

  • 请发布您的主 html 文件和模块配置。似乎有问题。
  • 好像是模块初始化有问题,请提供您的代码相关的模块配置
  • 没有其他模块配置
  • 你能在 plunker 中复制这个问题吗?这是一个你可以 fork 的空白模板:plnkr.co/edit/WprgipAdFBtxDKM6jogo?p=info
  • 你在某处声明了 ng-app 吗?

标签: javascript angularjs node.js angular-ui-router url-routing


【解决方案1】:

created working plunker,它确实使用与上述相同的 UI-Router 设置。一切正常。所以,我们现在应该知道,应该正确设置客户端。

主要和唯一的区别是,更明确的设置,允许我们在头部省略&lt;base href="/" /&gt;

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

或者我们可以使用 &lt;base&gt; 元素(检查 index.html &lt;head&gt;) int plunker

好像问题出在服务器端,请检查两次:

How to: Configure your server to work with html5Mode

【讨论】:

  • 这真是令人惊讶。请您尝试检查requireBase: true 和明确的&lt;base href="/" /&gt; 是否有效?如果是,那么我们应该只玩一下&lt;link&gt; 元素....我更新了我的答案并在其中包含了&lt;link href="style.css" rel="stylesheet" /&gt;...
  • 我通过将&lt;base&gt; 放在&lt;link&gt;' 标签之前来修复它
  • 干得好,先生!享受令人惊叹的 UI-Router ;)
猜你喜欢
  • 2018-04-10
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 2015-07-31
  • 2017-08-24
相关资源
最近更新 更多