簡體   English   中英

刷新頁面中沒有主題標簽的頁面不起作用

[英]Refresh page without hashtag in Angular not working

我有Spring + Angular + Rest webapp。 我以這種方式從網址中刪除哈希。

if(window.history && window.history.pushState) {
    $locationProvider.html5Mode(true);
}

在index.html中

 <base href="/webapptest/">

現在,主頁看起來不錯,並且一切正常。 看起來像: http://localhost:8080/webapptest/

問題是當我刪除主題標簽后,當我轉到第二頁時... http://localhost:8080/webapptest/page2

顯示首次頁面,但重新加載后...錯誤404。 我讀到這是服務器端的問題,因為我破壞了網址...但是我不知道要更改什么...這是Spring Controller:

@RestController
@RequestMapping(value="api/files")
public class FileController {

@RequestMapping( method = RequestMethod.GET)
public @ResponseBody() String getFile(HttpServletRequest request) throws      IOException  {
    String htmlString = "";
    try {....
 ...
return htmlString;
}

這是使用page2的控制器和方法,同一控制器也使用主頁,但使用另一種方法。 有誰知道什么是問題,以及如何解決沒有井號的重新加載頁面?

app.js:

uploadFile.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) {
$routeProvider
    .when('/', {
        templateUrl : 'resources/html/home.html',
        controller : 'uploadFileController'
    })
    .when('/page2', {
        templateUrl : 'resources/html/page2.html',
        controller : 'uploadFileControllerAdmin'
    })
    .otherwise({
        redirectTo: '/'
    });
if(window.history && window.history.pushState) {
    $locationProvider.html5Mode(true);
}
}])

最初請求/webapptest ,瀏覽器將請求發送到服務器(例如Spring App),並返回index.html

加載index.html和Angular應用程序/模塊后,它將處理所有與其路徑相對應的匹配請求-這是相關的Angular參考 ,特別是關於html5mode

請注意,在這種模式下,Angular會攔截所有鏈接(服從下面的“ Html鏈接重寫”規則),並以從未執行完整頁面重新加載的方式更新url。

因此,從您的Angular應用中,對/webapptest/page2任何請求都將匹配其路由

.when('/page2', {
    templateUrl : 'resources/html/page2.html',

並由Angular專門處理,觸發Angular請求相應的templateUrl- resources/html/page2.html

此時,URL將為/webapptest/page2 ,但是您的瀏覽器從未真正向服務器請求過該URL。 但是,當您單擊刷新時,瀏覽器將接管,在/webapptest/page2的歷史記錄/位置中/webapptest/page2您的服務器請求,我假設您的服務器沒有,所以您得到404。


要解決此問題,您需要將服務器配置為讓Angular處理對/webapptest/**所有請求,這基本上意味着您需要將所有/webapptest/**映射到index.html。

您可以有一個簡單的視圖控制器

@Controller
public class SpaController {

  @RequestMapping(value={"/webapptest/**"}, method=RequestMethod.GET)
  public String app() {
    return "index"; 
  }
}

或將以上映射添加到Spring ViewControllerRegistry(如果您已在使用的話)。


順便說一句-需要這張支票嗎?

if(window.history && window.history.pushState) {
    $locationProvider.html5Mode(true);
}

對於不支持html5mode的舊版瀏覽器,$ location不會退回到Hashbang模式嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM