javascript - Angular 路由结果为 404 - 无法获取

标签 javascript angularjs angular-ui-router

我正在尝试使用 Angulars ui-router 设置 url,以便我可以转到基本 url 或转到相同的基本 url + 参数。所以 - 我可以转到/test 或/test/1,它将转到同一页面 - 唯一的区别是 url 参数。所以到目前为止我有这个:

 .state('test', {
    url: '/test',
    templateUrl: 'views/test.html',
    controller: 'testCtrl'
})
.state('testState', {
    url: '/test/:id',
    templateUrl: 'views/test.html',
    controller: 'testCtrl'
});

/test 似乎工作正常,但是当我输入 test/1 时,它显示 cannot GET。这是因为我手动输入 url,而不是使用 ui-routers 内部链接 (ui-sref)。我这样说是因为我注意到当我输入 /test 时,它也是一样的。但是,当我使用使用 ui-sref 设置的页面上的链接时,测试和主页点击工作正常。我希望能够共享 test/:id 的 URL,因为这将是一个网络应用,登录的人可以在其中共享链接。

另外 - 是否有更好的方法将 test 和 testState 设置为 1 状态?谢谢!

最佳答案

你的问题不在 Angular 端,而是你的服务器(我根据响应措辞猜测 Node)。 Node/express/whatever 不知道将哪个文件发送到服务器进行 test/1。尝试放宽您的路由方案。我的意思是,设置代码,以便对 test* 的任何请求都解析为与 test/ 相同的文件。以下是 Express 应用程序中的示例:

/**
 * For any GET that we can't resolve to a static file, assume it's 
 * an attempt to go to an angular route
 */
app.get('*', function(req, res){
  res.sendfile(path_to_indexfile);
});

更新(讨论后):

或者你可以关闭 html5 模式 - 那么你不需要担心告诉你的服务器如何处理 /test/1 - Angular 将使用 /test/# !/1 这不会引起问题。

关于javascript - Angular 路由结果为 404 - 无法获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28769609/

相关文章:

Javascript:使用括号表示法动态选择变量

javascript - 无法将数据从 Node 服务器发送到ajax

php - $stateChangeStart 在从 Rest API 获取数据之前运行

angularjs - 取消 $transitions 更改 ui-router

javascript - AngularJS 嵌套 $state 问题

javascript - React router redux 链接更改路由,但不是组件

javascript - SVG 投影分层

javascript - 将数组样式查询参数传递给 Angularjs 中的资源

javascript - 在 ui-router 配置文件中使用 Angular-translate 的 $translate.use()

javascript - AngularJS UI-Router + 需要状态帮助