请参考:使用vue-cli脚手架建立Vue项目html
请参考:使用IntelliJ IDEA建立Spring Boot项目vue
打开命令行窗口,并进到到vue项目的目录下,
执行命令:npm install axios
(由于网速慢下载失败,因此用淘宝的仓库了)java
先打开Vue项目中config下的index.js:ios
而后修改内容:
target时spring服务端的地址和端口,下面的host和port是vue项目的地址和端口。web
再打开src下的main.js,引入axios,并进行相关设置:spring
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了:vue-cli
<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),这里就不赘述了。npm
咱们须要实现org.springframework.web.servlet.config.annotation.WebMvcConfigurer
接口来进行跨域访问的设置:json
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); } }
我为了方便就设成这样而已,实际开发需根据实际状况来进行设置。axios
先看看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的功能是将服务器端中某个文件夹里的文件(含子文件夹)显示在页面上,局域网内的用户能在线浏览。 目前只实现了将文件列出来和视频的在线观看,但大视频的加载速度有点慢,用手机端看的时候更慢,缘由待查。