gpt4 book ai didi

javascript - Angular 中没有主题标签的刷新页面不起作用

转载 作者:可可西里 更新时间:2023-11-01 17:36:29 25 4
gpt4 key购买 nike

我有 Spring+Angular+Rest webapp。我以这种方式从 url 中删除哈希标签 ..

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

在 index.html 中

 <base href="/webapptest/">

现在,主页看起来不错,一切正常。 看起来像:http://localhost:8080/webapptest/

问题是,在我删除主题标签后,当我转到第二页时... http://localhost:8080/webapptest/page2

第一次显示页面,但重新加载后...错误 404。我读到这是服务器端的问题,因为我更改了 url...但我不知道要更改什么...这是 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 的 Controller 和方法,同一个 Controller 也使用主页,但使用另一种方法。有人知道什么是问题以及如何解决没有主题标签的重新加载页面吗?

应用程序.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 reference ,特别是关于 html5mode

Note that in this mode, Angular intercepts all links (subject to the "Html link rewriting" rules below) and updates the url in a way that never performs a full page reload

因此,从您的 Angular 应用程序,对 /webapptest/page2 的任何请求都将匹配它的路由

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

并由 Angular 专门处理,这会触发 Angular 请求相应的 templateUrl -- resources/html/page2.html

此时 url 将是 /webapptest/page2,但您的浏览器实际上从未从您的服务器请求过它。但是当你点击刷新时,你的浏览器接管,在它的历史/位置中看到 /webapptest/page2 并从你的服务器请求它,我假设你的服务器没有所以你得到一个 404。


要解决这个问题,你需要配置你的服务器让 Angular 处理所有对 /webapptest/** 的请求,这基本上意味着你需要映射所有 /webapptest/** 到 index.html。

你可以有一个简单的 View Controller

@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);
}

对于不支持 html5 模式的旧版浏览器,$location 不会回退到 Hashbang 模式吗?

关于javascript - Angular 中没有主题标签的刷新页面不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30060376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com