企业项目管理、ORK、研发管理与敏捷开发工具平台

网站首页 > 精选文章 正文

若依框架-前端静态资源如何整合到后端访问

wudianyun 2024-12-20 11:11:28 精选文章 60 ℃

分离版本都是前端和后端单独部署的,但是有些特殊情况想把前端静态资源整合到后端。提供如下方案:

1、修改ruoyi-ui中的.env.production(二选一)

// 本机地址访问
VUE_APP_BASE_API = '/'
// 任意地址访问
VUE_APP_BASE_API = '//localhost:8080'

2、修改ruoyi-ui中的router/index.js,设置mode属性为hash

export default new Router({
  mode: 'hash',
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

3、执行bin\build.bat打包前端静态资源文件。

4、修改后端resources中的application.yml,添加thymeleaf模板引擎配置

spring:
  # 模板引擎
  thymeleaf:
    mode: HTML
    encoding: utf-8
    cache: false

5、修改后端ruoyi-admin/pom.xml,增加thymeleaf模板引擎依赖

<!-- spring-boot-thymeleaf -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

6、修改后端ResourcesConfig.java中的addResourceHandlers,添加静态资源映射地址

/** 前端静态资源配置 */
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");

7、修改后端SecurityConfig.java中的configure,添加允许访问的地址。

.antMatchers(
		HttpMethod.GET,
		"/*.html",
		"/**/*.html",
		"/**/*.css",
		"/**/*.js",
		"/static/**",
		"/",
		"/index"
).permitAll()


8、后端新建访问控制处理IndexController.java设置对应访问页面。

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController
{
    // 系统首页
    @GetMapping(value = { "/", "/index", "/login" })
    public String index()
    {
        return "index";
    }
}


9、整合前端dist静态资源文件到后端

  • 后端resources下新建templates目录,复制静态页面index.html过来。
  • 复制静态文件staticresources目录下。

10、启动测试访问地址

打开浏览器,输入:http://localhost:8080 能正常访问和登录表示成功。

注意

由于切换成了一个应用启动前后端,所以不需要通过代理跳转,前端组件如果用到process.env.VUE_APP_BASE_API可以进行删除。防止打包部署后访问不到后端。

例如:process.env.VUE_APP_BASE_API + "/common/upload" 换成 "/common/upload",还有哪里用到了自己全局搜索一下删除。

如果嫌麻烦还有一种简单的方式,将.env.productionVUE_APP_BASE_API改成空字符串。 VUE_APP_BASE_API = '',然后将index.html移动到static目录下,同时访问地址则变成 http://localhost:8080/index.html,另外IndexController.java可以删除。

参考:

https://doc.ruoyi.vip/ruoyi-vue/other/faq.html#%E5%89%8D%E7%AB%AF%E9%9D%99%E6%80%81%E8%B5%84%E6%BA%90%E5%A6%82%E4%BD%95%E6%95%B4%E5%90%88%E5%88%B0%E5%90%8E%E7%AB%AF%E8%AE%BF%E9%97%AE

最近发表
标签列表