Springboot+Vue+axios实现跨域访问(学习笔记)

创建一个简单的Vue项目

请参考:使用vue-cli脚手架创建Vue项目

创建一个简单的Spring Boot项目

请参考:使用IntelliJ IDEA创建Spring Boot项目

利用npm安装axios

打开命令行窗口,并进到到vue项目的目录下,
执行命令:npm install axios
(因为网速慢下载失败,所以用淘宝的仓库了)

实现跨域访问

Vue端的设置

先打开Vue项目中config下的index.js:

然后修改内容:
target时spring服务端的地址和端口,下面的host和port是vue项目的地址和端口。

再打开src下的main.js,引入axios,并进行相关设置:

import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'

Vue.config.productionTip = false

// 将axios挂载在Vue实例原型上
Vue.prototype.$axios = axios
// 超时终止请求
axios.defaults.timeout = 5000
axios.defaults.baseURL = 'http://192.168.1.106:2333'
// 设置请求头
axios.defaults.headers = {'Content-type': 'application/json;charset=UTF-8'}

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

然后就能在组件里使用axios了:

<template>
  <div>
    ...
  </div>
</template>

<script>
export default {
  data: function () {
    return {
    }
  },
  methods: {
    go: function (id) {
      this.$axios.get('/file/' + id).then(res => {
        console.log(res.data)
      })
    }
  }
}
</script>

<style scoped>
</style>

axios详细的用法可以参照官网:http://www.axios-js.com/docs
axios还能使用拦截器来拦截请求,从而修改请求头的配置或添加参数等(譬如可以利用拦截器来往请求头里设置token),这里就不赘述了。

Spring Boot服务器端的设置

我们需要实现org.springframework.web.servlet.config.annotation.WebMvcConfigurer接口来进行跨域访问的设置:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author ccneko
 * @since 2020/3/15 15:46
 */
@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer{

    @Override
    public void addCorsMappings(CorsRegistry registry){
        //设置允许跨域的路径
        registry.addMapping("/**")
                //设置允许跨域请求的域名
                .allowedOrigins("*")
                //这里:是否允许证书 不再默认开启
                .allowCredentials(true)
                //设置允许的方法
                .allowedMethods("*")
                //跨域允许时间
                .maxAge(3600);
    }

}

我为了方便就设成这样而已,实际开发需根据实际情况来进行设置。

试运行

先看看Spring Boot服务器端Controller的代码和访问结果。

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public FileVo getFilesById(@PathVariable(value = "id") String id) throws Exception{
    return this.fileService.findAccountListById(id);
}

再来看看Vue项目对应的访问结果:

跨域访问成功,

P.S.我这个demo的功能是将服务器端中某个文件夹里的文件(含子文件夹)显示在页面上,局域网内的用户能在线浏览。
目前只实现了将文件列出来和视频的在线观看,但大视频的加载速度有点慢,用手机端看的时候更慢,原因待查。

猜你喜欢

转载自www.cnblogs.com/minxiang-luo/p/12493392.html