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的功能是將服務器端中某個文件夾里的文件(含子文件夾)顯示在頁面上,局域網內的用戶能在線瀏覽。
目前只實現了將文件列出來和視頻的在線觀看,但大視頻的加載速度有點慢,用手機端看的時候更慢,原因待查。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM