网上流行的解决方案是将assetsPublicPath: '/'改成'./',下面说一下这个解决方案的弊端:

通常页面空白的问题出现大多数是由于Spring Boot端配置了server.servlet.context-path,上下文改变了css, js等文件的访问路径,文件无法加载导致index.html显示空白。'/'改成'./'是将绝对路径变为相对路径,可以动态适应Spring Boot端上下文的改变,这是为什么这个解决方案起作用的原因。

Vue项目部署在Spring Boot出现的另一个常见问题是当刷新浏览器的时候出现white label, 也就是404错误,解决的方案基本是把error page配置成为Vue的index.html。

这两个解决方案有冲突的地方,当router出现子路径的时候刷新浏览器,error page会指向Vue的index.html页面,此时页面中访问css,js文件的路径是相对路径,也就是上下文路径+router子路径,这将导致css,js再次无法正常加载,这就是相对路径的弊端。

由于router会出现子路径,因此必须保证assetsPublicPath为绝对路径,下面讲一下保持绝对路径的解决方案:

1 假设Spring Boot端配置server.servlet.context-path: api, 对应Vue的/config/index.js中assetsPublicPath: '/'改成 '/api/'

2 router/index.js中配置base: '/api/', 这是保证浏览器刷新时上下文参数和router跳转路径一致。

3 对于Ajax请求需要配置baseURL, 如果使用Axios, 可以采用如下方法在main.js中配置

// http request 拦截器

Axios.interceptors.request.use(

config => {

if (localStorage.getItem('id_token')) {

config.headers.Authorization = localStorage.getItem('id_token')

}

config.baseURL = '/api'

return config

},

err => {

return Promise.reject(err)

})

4 另外需要注意的一点,按照Spring Boot默认配置, 在Vue端/config/index.js中assetsSubDirectory: 'static'要改变为其它字符,比如:'content', 'vue', 'api'等等。

5 试过将assetsSubDirectory配置为空,它和另一个css图片加载的方案有冲突,图片加载解决方案是在/build/util.js中加一行配置

// Extract CSS when that option is specified

// (which is the case during production build)

if (options.extract) {

return ExtractTextPlugin.extract({

use: loaders,

fallback: 'vue-style-loader',

publicPath: '../../'

})

结尾附上Spring Boot端将error page指向Vue的index.html代码:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;


@Configuration
public class ServletConfig {
    private static final Logger logger = LoggerFactory.getLogger(ServletConfig.class);
    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
        logger.info("come to 404 error page");
        return factory -> {
            ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
            factory.addErrorPages(error404Page);
        };

    }
}

总结:以上是Vue项目部署于Spring Boot中常见的几个问题的解决方案。如果遇到其它部署问题欢迎留言!

Cheers!

Logo

前往低代码交流专区

更多推荐