前后端整合部署
今天遇到一个需求是为了部署的方便,领导那边要求我这边将前后端代码整合在一起就只需要部署后端服务即可,后端我用的是spring boot项目,前端是vue,以下是实现步骤:
1. 前端 Vue 项目打包
首先需要前端将 Vue 项目打包,生成静态资源文件。
1.1 在 Vue 项目中执行打包命令
npm run build
这条命令会在
dist目录下生成打包后的静态资源文件,包括index.html和相关的静态文件(如 CSS、JS)。
2. 将dist内的资源放到 Spring Boot 静态目录中
Spring Boot 默认会将静态资源目录设置为 src/main/resources/static,你可以将 Vue 打包后的文件直接拷贝到这个目录下。
拷贝打包文件
将 dist 文件夹中的所有文件拷贝到 Spring Boot 项目的 src/main/resources/static 目录中。
目录结构示例如下:
src
└── main
├── java
├── resources
│ ├── static <-- 放置 Vue 打包后的文件
│ │ ├── index.html
│ │ ├── js/
│ │ ├── css/
│ │ ├── img/
│ ├── application.yml
3. 配置 Spring Boot 处理前端页面请求
Spring Boot 默认会将静态资源中的 index.html 作为默认页面加载,但你需要确保请求路径正确映射。
3.1 配置 Spring Boot 的首页映射
在 Spring Boot 的主类或配置类中,设置首页映射路径:
这里是实现WebMvcConfigurer,通过重写addViewControllers方法,然后对注册器进行设置。
将根路径 “/” 映射到静态资源下的 index.html
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 将根路径 "/" 映射到静态资源下的 index.html
registry.addViewController("/").setViewName("forward:/index.html");
}
}
4. 启动 Spring Boot 项目
运行 Spring Boot 项目,访问:
根据自己的项目的访问路径进行调整。
http://localhost:8053/v1/outsouced/
Spring Boot 会自动加载 static 目录下的 index.html 文件,前端 Vue 项目就会运行起来。
5. 接口请求跨域处理
如果 Vue 前端代码中需要请求 Spring Boot 后端的接口,确保后端支持跨域请求,或者在生产环境中使用同一域名即可。
Spring Boot 跨域配置
如果有跨域问题,可以在 Spring Boot 后端配置 CORS 支持:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许所有路径
.allowedOrigins("*") // 允许所有域名
.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的方法
.allowedHeaders("*"); // 允许的请求头
}
};
}
}
6. 总结
通过上述步骤,就将前端 Vue 项目和后端 Spring Boot 项目整合在一起:
- 前端 Vue 项目打包,生成静态资源。
- 将打包后的文件放到 Spring Boot 项目的
src/main/resources/static目录。 - 配置 Spring Boot 映射根路径到
index.html。 - 运行 Spring Boot 项目,前后端一起运行。
这样前端的页面和后端接口可以通过 同一个服务器 提供,部署也会更加方便。
更多推荐


所有评论(0)