Vue + Spring Boot History模式 打包后 刷新404问题
此次主要是vue项目打包后,放在spring-boot后端,整合一起打包。访问页面,刷新出现404的情况。此处不用纠结是否真的前后端分离的情况一、修改history模式修改router\index.js,加入mode: 'history这句话。整体代码如下:Vue.use(Router)const VueRouterPush = Router.prototype...
此次主要是vue项目打包后,放在spring-boot后端,整合一起打包。访问页面,刷新出现404的情况。此处不用纠结是否真的前后端分离的情况
一、修改history模式
修改 router\index.js
,加入 mode: 'history
这句话。整体代码如下:
Vue.use(Router)
const VueRouterPush = Router.prototype.push
Router.prototype.push = function push (to) {
return VueRouterPush.call(this, to).catch(err => err)
}
const constantRouterMap =
[
// {path: '/testModule', component: testModule },
{path: '/demo', component: demo },
{path: '/treeDemo',component: treeDemo},
{path: '/errorTree',component: errorTree},
{path: '/errorDictionary',component: errorDictionary},
{path: '/templateDemo',component: templateDemo}
]
export default new Router({
mode:'history',
base:'/my-app/',
routes: constantRouterMap
})
运行项目,http://localhost:8082/ 显示页面。
二、添加base属性
如果不是放在后台,应该是不需要加此属性
在mode: 'history',之后添加base: '/后端服务器的上下文/'。
由于vue项目打包后,是放在后端。启动后端,访问
http://localhost:8999/my-app/index.html
这个/my-app/就是spring-boot中设置的上下文
三、后端处理
在后端项目中创建一个配置类,新建实现 ErrorPageRegistrar
接口的类 ErrorConfig,把默认的错误页面设置为 /index.html
,代码如下;
package com.oneapp.app.infrastructure.config;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
@Component
public class ErrorConfig implements ErrorPageRegistrar {
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
registry.addErrorPages(error404Page);
}
}
这样重启后台,访问,点击刷新,应该就不会出现404的情况了
写在末尾
内容参考https://learner.blog.csdn.net/article/details/89422585。在此感谢作者,其系列有很多精华,我也在努力学习中。再次感谢
更多推荐
所有评论(0)