栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > Vue.js

前后端分离 Spring Boot + Vue 开发单页面应用 个人总结(二)

Vue.js 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

前后端分离 Spring Boot + Vue 开发单页面应用 个人总结(二)

2018/01/30 更新

关于跨域:在实际开发过程中,发现跨域问题并不是那么好解决的 因为Springboot安全控制框架使用了Securtiy,它的身份认证基于 JSESSIonID 而axios框架默认是不发送cookie的,因此需要在axios配置中添加

axios.defaults.withCredentials = true

然而因为跨域策略问题,Springboot后端跨域设置也要修改

@Configuration
public class CorsConfig {
    
    private CorsConfiguration buildConfig() {
 CorsConfiguration corsConfiguration = new CorsConfiguration();
 // addAllowedOrigin 不能设置为* 因为与 allowCredential 冲突
 corsConfiguration.addAllowedOrigin("http://localhost:9528");
 corsConfiguration.addAllowedHeader("*");
 corsConfiguration.addAllowedMethod("*");
 // allowCredential 需设置为true
 corsConfiguration.setAllowCredentials(true);
 return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
 UrlbasedCorsConfigurationSource source = new UrlbasedCorsConfigurationSource();
 source.registerCorsConfiguration("
new Vue({
  el: '#app',
  router,
  store,
  template: '',
  components: { App }
})

App.vue ,.vue后缀名的文件是Vue提供的单文件组件方式单文件组件 核心由template标签组成,script标签可以挂载Vue实例等脚本,形成组件,style标签可以用来写css。
因为本人做页面水平有限,前端Demo做得非常丑,主要是记录是各个模块的配置,敬请谅解!






  #app {
    font-family: Helvetica, sans-serif;
    text-align: center;
  }
  .main-container {
    height: 100%;
    border: 1px solid #eee;
    margin: 10px 50px 0 50px;
  }
  
  .el-container, .el-aside {
    border: 1px solid red;
  }

剩下的源码我就不贴在文章中了,登陆实例大量参考 tong2-family
thaks again!
这里重点讲通过axios与SpringBoot服务器通信会遇到两个问题

  • 一是跨域问题
    开发过程中,前后端通常都是启用单独的端口,因此会有跨域的问题,在第一篇文章的最后,配置了一个CrosConfig就跨域解决了
  • 二是由于Content-type的问题,会导致controller无法拿到post请求的数据,网络上解决方法很多试了都不可以,最后我尝试了一个,测试是可以通过的
    axios有拦截器功能,可以方便得为全局做配置
    // 设置content-type
    // 这里处理的是 针对SpringMVC Controller 无法正确获得请求参数的问题
    axios.interceptors.request.use(
    config => {
    let data = config.data
    let key = Object.keys(data)
    // 重写data,由{"name":"name","password":"password"} 改为 name=name&password=password
    config.data = encodeURI(key.map(name => `${name}=${data[name]}`).join('&'))
    // 设置Content-Type
    config.headers = {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    }
    return config
    },
    error => {
    return Promise.reject(error)
    }
    )
项目展示及源码
  • 服务端代码 spring-vue-demo
  • 前端项目代码 spring-vue-demo
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/240797.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号