页面刷新使用springboot应用程序在angular5中给出404

时间:2018-03-20 05:23:48

标签: spring-boot angular2-routing angular5

我在端口8080上的springboot中运行了一个Web服务。当我点击url下面时,它工作正常:

http://localhost:8080/app,我将网址重定向到以下位置:

http://localhost:8080/myHome/home

现在,当我刷新页面时,我得到了404

下面是我的index.html的内容:

  <base href="/myHome">

的package.json:

"scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json",
    "build": "ng build --dev --deploy-url=\"/app/\"",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "protractor"
},

我曾尝试使用

中提到的LocationStrategy

Angular 2: 404 error occur when I refresh through the browser,但它不适合我。

4 个答案:

答案 0 :(得分:1)

由于弹簧检查资源/ myHome / home而导致错误,但未找到

资源位置是/ app,因此您可以修复 -

1) Use hashRouting in angular application 

2) Redirect to '/' in springboot aplication when requesting came from another url /**

答案 1 :(得分:0)

我在Spring Boot 2中遇到了同样的问题。我已将资源解析器位置添加为静态目录,并且如果与任何文件都不匹配,则加载index.html

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/**/*")
                .addResourceLocations("classpath:/static/")
                .resourceChain(true)
                .addResolver(new PathResourceResolver() {
                    @Override
                    protected Resource getResource(String resourcePath, Resource location) throws IOException {
                        Resource requestedResource = location.createRelative(resourcePath);
                        return requestedResource.exists() && requestedResource.isReadable() ? requestedResource : new ClassPathResource("/static/index.html");
                    }
                });



}

答案 2 :(得分:0)

向您的routerModule添加{useHash:true},它对我有用:

导入:[RouterModule.forRoot(routes,{useHash:true})]

答案 3 :(得分:0)

这是我发现有效的解决方案:虽然这是在kotlin中。但之间不难改变。

https://github.com/emmapatterson/webflux-kotlin-angular/blob/master/README.md

希望这会有所帮助! 主要代码是:

import org.springframework.context.annotation.Configuration
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.WebFilter
import org.springframework.web.server.WebFilterChain
import reactor.core.publisher.Mono

private const val INDEX_FILE_PATH = "/index.html"

@Configuration
internal class StaticContentConfiguration(): WebFilter {

    override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
        val path = exchange.request.uri.path
        if (pathMatchesWebAppResource(path)) {
            return redirectToWebApp(exchange, chain)
        }
        return chain.filter(exchange)
    }

    private fun redirectToWebApp(exchange: ServerWebExchange, chain: WebFilterChain) = 
    chain.filter(exchange.mutate()
        .request(exchange.request.mutate().path(INDEX_FILE_PATH).build())
        .build())

    private fun pathMatchesWebAppResource(path: String) =
        !path.startsWith("/api") && path.matches("[^\\\\.]*".toRegex())
}