SpringCloud工程搭建之前后端分离搭建(可选)

六、前后端分离搭建(可选)

    完整工程源码:https://gitee.com/forwardxiang/spring-cloud-demo.git

6.1 创建前端工程

6.1.1 导入依赖

    由于是纯前端部署,除了继承父工程依赖外,只需要引入web依赖即可: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

6.1.2 编写启动类

    不需要Eureka等其他微服务,因此仅给出springboot的启动类注解即可: @SpringBootApplication public class LayUIApplication { public static void main(String[] args) { SpringApplication.run(LayUIApplication.class, args); } }

6.2 配置前端工程

6.2.1 配置前端服务的端口

    没有其他微服务,仅仅提供web访问,因此application.yml只需要配置端口即可: server: port: 80

6.2.2 导入前端资源

    在springboot默认静态资源目录: #查找源码中ResourceProperties类 classpath:/META-INF/resources/ classpath:/resources/ classpath:/static/ classpath:/public 将js/css/图片等资源导入到static目录中,将HTML页面文件导入到public目录,结构如下:

6.3 前端服务请求

    前端采用layui框架,简单易用,但是需要注意有些细节,例如layui表单渲染的下拉框,在使用jQuery选中并更改数据后,需要使用layui表单重新(form.render(‘select’))渲染才会起作用。 由于后端服务与本前端不在一个同源域中,因此需要在后端服务中配置跨域。以下是前端中发起Ajax的例子: $.ajax({ type: "POST", url: "http://127.0.0.1:9091/bill/update" , data: JSON.stringify(data.field), dataType: "json", contentType: "application/json; charset=UTF-8", success: function (vo) { if (vo.code === 200) { window.location.href = "table.html"; } else { layer.alert("账单信息更新失败!" + vo.msg); } } });

6.4 后端服务跨域配置

    为了简化问题,这里先介绍没有网关,前端直接访问后端业务微服务的情况下,使用注解的方式配置跨域: @CrossOrigin //也可以注解在具体的方法上 @RefreshScope @RestController @RequestMapping("bill") public class BillController { //省略 } 当外部访问经过网关时,无需在业务微服务配置跨域,若这两处都配置了跨域反而可能会因为回复的头部信息重复导致前端报错(除非在Gateway配置了去重操作),具体网关配置参考:
经验分享 程序员 微信小程序 职场和发展