[英]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.