我目前正在处理一个项目,该项目在后端使用 SpringBoot,在前端使用 HTML5 和 Angular 2。
部署项目后,在浏览器中导航时一切正常,直到我按下重新加载按钮。浏览器将显示错误页面。
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon May 08 10:16:14 CDT 2017
There was an unexpected error (type=Not Found, status=404).
No message available
这显然是由于使用 HTML 5 历史 API 在浏览器 URL 中存储客户端导航造成的。
因此,当我开始点击页面上的项目时,我会看到 URL 自动附加自身。
但是,当点击刷新时,这会成为一个问题,完整的附加 URL 被发送到无法理解的服务器,因为该附加 URL 的特定映射不存在。
是否有更新服务器端配置的修复程序,以便任何未知的 URL 返回根 index.html View 的 View ?
例如,当我点击刷新时,查询的 URL 只是根 url http://localhost:8080/root
,而不是附加的 URL。
这将使浏览器正确导航,而不是尝试在服务器端进行导航。
最佳答案
因为您似乎只使用 SpringBoot 作为后端,您可以将所有请求重定向到 index.html
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Controller
static class Routes {
@RequestMapping(value = "/**", method = RequestMethod.GET)
public String index() {
return "index.html";
}
}
}
或者重写 ErrorController
来捕捉你看到的 /error
并重定向到你的索引
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class OverrideController implements ErrorController {
@RequestMapping("/error")
public String index() {
return "index.html";
}
@Override
public String getErrorPath() {
return "index.html";
}
}
但我建议通过使用可能与 Nginx 一样基本的东西来为您的 Angular 应用程序提供服务,从而将前端与后端完全分开,因为您只需要提供静态文件。 SpringBoot 似乎有点矫枉过正或者不适合这个目的。
这里配置不错example您可以为此目的进行调查,这基本上是 index.html
server {
server_name yoursite.com;
root /usr/share/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
关于javascript - HTML5 History API 自动路由刷新错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43851499/