Springboot+Vue+axios實現跨域訪問(學習筆記)

建立一個簡單的Vue項目

請參考:使用vue-cli腳手架建立Vue項目html

建立一個簡單的Spring Boot項目

請參考:使用IntelliJ IDEA建立Spring Boot項目vue

利用npm安裝axios

打開命令行窗口,並進到到vue項目的目錄下,
執行命令:npm install axios
(由於網速慢下載失敗,因此用淘寶的倉庫了)java

實現跨域訪問

Vue端的設置

先打開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

Spring Boot服務器端的設置

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

相關文章
相關標籤/搜索