网上流行的解决方案是将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中配置 : \'/api/\', 这是保证浏览器刷新时上下文参数和router跳转路径一致。
3 对于Ajax请求需要配置 URL, 如果使用Axios, 可以采用如下方法在main.js中配置
// http request 拦截器
Axios.interceptors.request.use(
config => {
if (localStorage.getItem(\'id_token\')) {
config.headers.Authorization = localStorage.getItem(\'id_token\')
}
config. URL = \'/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.spring work.boot.web.server.ConfigurableWebServerFactory;
import org.spring work.boot.web.server.ErrorPage;
import org.spring work.boot.web.server.WebServerFactoryCustomizer;
import org.spring work.context.annotation.Bean;
import org.spring work.context.annotation.Configuration;
import org.spring work.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出现页面空白问题的解决方案,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
继续阅读与本文标签相同的文章
易语言防止助手探测窗口的代码
黑客找到Switch内核漏洞 但表示不会发布
-
Linux rsyslog 简记
2026-05-19栏目: 教程
-
Oracle 左连接(left join) 排序问题
2026-05-19栏目: 教程
-
Java同步:synchronized解析
2026-05-19栏目: 教程
-
Oracle查询结果集无法被redis缓存序列化问题
2026-05-19栏目: 教程
-
Knative Serving 进阶: Knative Serving SDK 开发实践
2026-05-19栏目: 教程
