一、概述
项目vue + springboot,前后端分离项目;但部署时,不想用nginx代理,想要前端npm run build:prod后,将dist的目录整体复制到SpringBoot项目中,通过静态资源映射,节省一个端口。
二、操作步骤
1、前端
1)修改服务访问前缀
VUE_APP_CONTEXT_PATH = '/dist/'
说明1: 必须增加此前缀,用于区分是前端的请求还是后端的请求;dist可以根据项目自行定义;修改后注意修改后端的代码;
说明2: npm run build:prod直接打包
说明3: 注意下前后都有【/】,是【/dist/】,不是【/dist】
~~
2、后端
1)配置application.yml
spring:
web:
resources:
# jar包同级目录,static文件夹
static-locations: "classpath:/dist/"
mvc:
# 静态资源匹配,前端
static-path-pattern: /**
说明1: pattern匹配的所有,所以会拦截所有请求,包含前端/web以及后端/business等请求
;区别在于,前端都是get请求,后端有get有post,所以需要通过前缀进行区分;
说明2: dist整体复制就可以,位于/resouces下;【/resources/dist】
2)copy请求类SysIndexController
package com.hg.demo.config;
import groovy.util.logging.Slf4j;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
/**
* web mvc config
*
* @author hgsuper
*/
@Slf4j
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/dist/**").addResourceLocations("classpath:/dist/");
WebMvcConfigurer.super.addResourceHandlers(registry);
}
@Bean
public ErrorViewResolver errorViewResolver() {
return (request, status, model) -> {
if (status.value() != 404) {
return null;
}
String uri = (String) model.get("path");
return new ModelAndView("/dist/index.html", HttpStatus.OK);
};
}
}
说明1: 拦截前端访问的请求,然后重定向到index.html
说明2: 通过【WebMvcConfig】的方式配置;用的是若依的框架
说明3: 此配置类,放到controller所在模块;子模块也可以,子模块注意依赖生效
~~