Spring Boot 页面刷新是用springboot应用程序在angular5中给出404

piok6c0g  于 2022-11-05  发布在  Spring
关注(0)|答案(4)|浏览(129)

我有一个网络服务运行在端口8080上的springboot。当我点击下面的url它工作正常:
http://localhost:8080/app,我将URL重定向到下面:
http://localhost:8080/myHome/home
404页面找不到了
以下是我的索引.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,但它不适合我。

krugob8w

krugob8w1#

我在Sping 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");
                    }
                });

}
mwngjboj

mwngjboj2#

将{ useHash:true }添加到您的routerModule,它对我有效:
导入:[路由器模块.forRoot(路由,{ useHash:true})]

bvn4nwqk

bvn4nwqk3#

由于Spring检查资源/myHome/home而导致错误发生,但未找到
资源位置为/app,因此您可以修复-

1) Use hashRouting in angular application

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

mnemlml84#

这就是我找到的解决方案:这是在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())
}

相关问题