我在刷新瀏覽器之後保持空白頁面空白時遇到了問題。
當用戶訪問/user/:username
,profile.html
加載。它在第一次加載時按預期工作,但如果我刷新頁面,則屏幕上會留下一個原始JSON輸出(以前,它只會說「null
」)。
有關進一步情況下,我在home.html
文件有一個ng-href
:
<h3>View your profile page <a ng-href="/user/{{user.username}}">here</a>.</h3>
對應的角文件:
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的使用而持續存在。
嘗試使用此middlware https://github.com/bripkens/connect-history-api-fallback在你的服務器的NodeJS – Leguest
好了,我掠過文檔。該解決方案可能只解決部分問題。 「1.請求是GET請求 2.接受文本/ html, 3.不是直接文件請求,即請求的路徑不包含。(DOT)字符和 4.不匹配模式提供options.rewrites(請參閱下面的選項)「 我打算利用完整的CRUD操作,所以只限於一個'GET'請求將不會是理想的。如果我使用諸如'user.username'之類的路徑(上面的#3),我可能會遇到問題。 – Farid
感謝您的快速回復和鏈接!請忽略上述評論。我無法進一步編輯它。以下是我的意思寫作: 我瀏覽了文檔,此解決方案可能只解決部分問題,因爲我計劃使用完整的CRUD操作。 – Farid