Springboot+Vue前后端分离开发--合并打包(无跨域)

碎碎念:最近参与导师一个基于spring boot+vue2的前后端分离项目,因为本人项目经验欠缺,打包部署时遇到各种跨域问题,请教学长花了好长时间才把项目部署到服务器.......经过这次艰难的部署过程,老师又对我说:这样前后端分离好像对我们没什么好处,部署还存在各种跨域问题,你能不能想办法给它改成不分离项目?于是经过查阅各种博客经验总结以及个人能力范围内,我只好按照开发分离、部署不分离的方法解决,spring boot整合vue静态资源打成一个jar包,无跨域请求即可快速部署,且有利于后续的开发和维护工作。

第一步:前端项目打包

1、vue.config.js配置

let proxyObj = {};
const CompressionPlugin = require("compression-webpack-plugin");
proxyObj['/ws'] = {
    ws: true,
    target: "ws://localhost:8081"
};
proxyObj['/'] = {
    ws: false,
    target: 'http://localhost:8081',
    changeOrigin: true,
    pathRewrite: {
        '^/': ''
    }
}
module.exports = {
    productionSourceMap: false,
    devServer: {
        host: 'localhost',
        port: 8080,
        proxy: proxyObj
    },
    
}

这里很多博客说要修改vue.config.js文件里的publicPath修改为publicPath: './',可能是大家的代码结构不同这里给我带来很多麻烦(尝试了很多次后端就是访问不到静态资源,哭晕在厕所),我这里前端不需要修改任何配置,按前后端分离开发时的打包配置就好。

2、运行npm run build,生成的静态资源存放在dist文件夹下

 3、将dist文件下的所有文件复制到spring boot下的resources文件夹下的static目录下

     可以打开index.html文件查看一下访问路径,注意没有/static

   

 4、因为本项目使用了Spring Security,修改SecurityConfig允许访问各种类型静态资源

 @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**", "/js/**", "/static/index.html", "/img/**", "/fonts/**", "/static/favicon.ico", "/verifyCode");
        web.ignoring().antMatchers("/swagger-resources/**");
        web.ignoring().antMatchers("/v2/**");
        web.ignoring().antMatchers("/**/*.json");
        web.ignoring().antMatchers("/index.html");
        web.ignoring().antMatchers("/global/**","/static/**");
    }

 5、添加访问静态页面配置WebMvcConfig

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addViewControllers(ViewControllerRegistry registry) {
        // TODO Auto-generated method stub
        // 注册访问 /login 转向 page-login.html 页面
        registry.addViewController("/login").setViewName("page-login.html");
        super.addViewControllers(registry);
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        // TODO Auto-generated method stub
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        super.addResourceHandlers(registry);
    }

}

6、修改application.properties添加静态资源路径

spring.mvc.static-path-pattern=/static/**
spring.web.resources.static-locations=classpath:/static

7、启动后端

 8、打开浏览器输入http://localhost:8081/index.html#/

      注意,我这里是hash模式,history模式输入http://localhost:8081/index.html/

      即可访问系统页面

参考:

Spring Security 静态资源访问_weixin_30627341的博客-CSDN博客 

后记      求助!!!!!!

接下来我想把index.html从地址栏去掉该怎么做,请各位大佬给与指导帮助~

 

猜你喜欢

转载自blog.csdn.net/acx0000/article/details/125787668