我正在尝试在Google App Engine(标准版)上部署带有Java后端的Angular 4应用。一切正常,除非我尝试重新加载页面。发生的事情是对例如应将myapp.com/some/page重定向到myapp.com/index.html,以便Angular应用响应。
据我所知,如果使用app.yaml配置文件,除了Java(使用appengine-web.xml和web.xml)之外,所有支持的语言都可以使用。
可以使用appengine-web.xml完成吗?用其他方式吗?
答案 0 :(得分:2)
如果要保留默认的“ HTML5 pushState”样式的PathLocationStrategy,则需要在后端实现重定向。基本上,您需要添加带有“ / *”作为URL模式且具有以下行为的过滤器或servlet:
public class SinglePageAppFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
RequestDispatcher dispatcher = servletRequest.getRequestDispatcher("/");
dispatcher.forward(servletRequest, servletResponse);
}
}
答案 1 :(得分:1)
是的,您必须使用HashLocationStrategy而不是默认的PathLocationStrategy。
Angular的文档:https://angular.io/guide/router#appendix-locationstrategy-and-browser-url-styles
基本上,您只需告诉RouterModule在AppRoutingModule中使用HashLocationStrategy:
@NgModule({
imports: [RouterModule.forRoot(routes, {useHash: true})],
exports: [RouterModule]
})
export class AppRoutingModule {
}
我希望它有所帮助
答案 2 :(得分:0)
作为对Gwendal Le Cren的回答的后续工作,我做到了这一点,并且还需要过滤器做一些其他事情,因此将其放在下面。
// Filter all paths.
@WebFilter("/*")
public class SinglePageAppFilter implements Filter {
@Override
public void doFilter(
ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
// Get the end part of the path e.g. /api for API requests, /devices for the devices page etc.
String path = ((HttpServletRequest) servletRequest).getServletPath();
// Continue with the intended action if an API request.
if (path.startsWith("/api")) {
filterChain.doFilter(servletRequest, servletResponse);
}
// Otherwise, send the result as if requesting the '/' path.
else {
RequestDispatcher dispatcher = servletRequest.getRequestDispatcher("/");
dispatcher.forward(servletRequest, servletResponse);
}
}
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void destroy() {}
}