javascript - html5模式下的AngularJS路由错误

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

这是我的前端 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"));

最佳答案

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

主要且唯一的区别是,更明确的设置,这允许我们省略 <base href="/" />在脑子里

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

或者我们可以使用<base>元素(检查index.html <head> ) int plunker

看来问题出在服务器端,请检查两次:

How to: Configure your server to work with html5Mode

关于javascript - html5模式下的AngularJS路由错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27691684/

相关文章:

javascript - AngularJS:使用 Transclude: 'element' 替换元素,但不使用已弃用的 'replace' ?

javascript - AngularJS:使用自定义服务转换 $resource 中的响应

javascript - 如何禁用SSL验证nodejs Loopback Request Plugin

javascript - Process.domain 在 Node 0.10 中未定义

javascript - 解析函数返回空 Promise

javascript - 我不明白为什么我的快速路由在发送后遇到 'can' t set headers'

javascript - VALue 不适用于使用 Jquery 代码的输入

javascript - 如何将函数名称作为参数传递,然后再引用该函数?

javascript - 固定菜单溢出移动浏览器和不可滚动

javascript - 用户界面路由器 : Transform parameter from URL