【发布时间】:2017-09-24 21:54:22
【问题描述】:
刷新浏览器后,我无法让我的一个页面保持空白。
当用户访问/user/:username 时,会加载profile.html。它在第一次加载时按预期工作,但如果我刷新页面,我会在屏幕上留下原始 JSON 输出(以前,它只会显示“null”)。
为了进一步了解,我的home.html 文件中有一个ng-href:
<h3>View your profile page <a ng-href="/user/{{user.username}}">here</a>.</h3>
对应的Angular文件:
var app = angular.module('social', ['ngRoute', 'ngCookies'])
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/login', {
templateUrl: 'login.html',
controller: 'LoginController'
})
.when('/signup', {
templateUrl: 'signup.html',
controller: 'SignupController'
})
.when('/user/:username', {
templateUrl: 'profile.html',
controller: 'UserProfileController'
})
$locationProvider.html5Mode(true)
})
我的控制器:
app.controller('UserProfileController', function($http, $scope, $cookies, $rootScope, $routeParams) {
console.log("$cookies.get('currentUser')")
console.log($cookies.get('currentUser'))
function getCurrentUser() {
$http.get('/user/' + $routeParams.username).then(function(res) {
console.log('res.data in the user profile controller')
console.log(res.data)
$scope.user = res.data
})
}
if ($cookies.get('currentUser') != undefined) {
getCurrentUser()
} else {
console.log("No one is here.")
}
})
我通过删除$locationProvider.html5Mode(true) 并使用ng-href="#/user/{{user.username}}" 来实现此功能,这意味着在页面刷新时不会丢失任何数据,并且我不会出现空白屏幕。但是,问题是 # 出现在 URL 中,这是我最终不想要的。显然,如果我将这样的应用程序推送到生产环境,我不希望# 出现在 URL 中。如果在开发过程中需要他们,我可以接受。
我还应该注意,我只有/user/:username 有这个问题。我的所有其他路由(/、/login 和 /signup)都按预期工作,这意味着刷新后页面不会变为空白,并且由于使用了 cookie,所有数据都会保留。
【问题讨论】:
-
尝试在你的nodejs服务器中使用这个中间件github.com/bripkens/connect-history-api-fallback
-
好的,所以我浏览了文档。该解决方案可能只能解决部分问题。 "1. 请求是 GET 请求 2. 接受 text/html, 3. 不是直接文件请求,即请求的路径不包含 . (DOT) 字符和 4. 不匹配选项中提供的模式.rewrites(参见下面的选项)”我计划使用完整的 CRUD 操作,因此仅限于
GET请求并不理想。如果我使用user.username(上面的#3)之类的路径,我也可能会遇到问题。 -
感谢您的快速回复和链接!请忽略以上评论。我无法进一步编辑它。这就是我要写的内容:我浏览了文档,这个解决方案可能只能解决部分问题,因为我计划使用完整的 CRUD 操作。
标签: angularjs node.js ngroute route-provider angular-cookies