【问题标题】:webflux resources router doesn't work as expectedwebflux 资源路由器无法按预期工作
【发布时间】:2019-12-05 05:21:49
【问题描述】:

我正在尝试使用 webflux 做一些非常简单的事情——提供静态页面

文件夹结构

-- resources
  -- public
     myPage.html  
    -- css
       style.css

路由器

@Bean
public RouterFunction<ServerResponse> htmlRouter(@Value("classpath:/public/myPage.html") Resource html) {
    return route(GET("/path/myPage"),
        request -> ok().contentType(MediaType.TEXT_HTML).bodyValue(html));
 }

@Bean
public RouterFunction<ServerResponse> imgRouter() {
  return RouterFunctions.resources("/**", new ClassPathResource("/public/"));
}

HTML sn-p

<header>
  <link rel="stylesheet" href="css/style.css">
  ...
</header>

调用 http://example.com/path/myPage 确实为页面提供服务,但 css 部分得到 404

logging.level.org.springframework.web: TRACE 上运行,我可以看到styles.css 被解析为/path/css/style.css,而不是在/public/css/style.css 下搜索,这是我的问题。

Error has been observed at the following site(s):
    |_ checkpoint ⇢ org.springframework.boot.actuate.metrics.web.reactive.server.MetricsWebFilter [DefaultWebFilterChain]
    |_ checkpoint ⇢ HTTP GET &quot;/path/css/style.css&quot; [ExceptionHandlingWebHandler]

【问题讨论】:

    标签: spring-boot spring-webflux


    【解决方案1】:

    在你的 HTML sn-p 中,你应该使用这样的绝对路径:

    <link rel="stylesheet" href="/css/style.css">
    

    使用相对路径css/styles.css 让您的浏览器认为它应该请求相对于当前页面的资源,因此/path/css/style.css。问题不在您的路由器中,而直接在您的模板中。

    【讨论】:

      猜你喜欢
      • 2016-07-09
      • 2012-10-04
      • 1970-01-01
      • 2021-10-03
      • 2021-03-04
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多