Vue+SpringBoot先後端分離中的跨域問題

在先後端分離開發中,須要前端調用後端api並進行內容顯示,若是先後端開發都在一臺主機上,則會因爲瀏覽器的同源策略限制,出現跨域問題(協議、域名、端口號不一樣等),致使不能正常調用api接口,給開發帶來不便。前端

封裝api請求vue

 1 import axios from 'axios'
 2 
 3 //axios.create建立一個axios實例,並對該實例編寫配置,後續全部經過實例發送的請求都受當前配置約束
 4 const $http = axios.create({
 5     baseURL: '',
 6     timeout: 1000,
 7     //headers: {'X-Custom-Header': 'foobar'}
 8 });
 9 
10 // 添加請求攔截器
11 $http.interceptors.request.use(function (config) {
12     // 在發送請求以前作些什麼
13     return config;
14 }, function (error) {
15     // 對請求錯誤作些什麼
16     return Promise.reject(error);
17 });
18 
19 // 添加響應攔截器
20 $http.interceptors.response.use(function (response) {
21     // 對響應數據作點什麼
22     return response.data;   //返回響應數據的data部分
23 }, function (error) {
24     // 對響應錯誤作點什麼
25     return Promise.reject(error);
26 });
27 
28 export default $http

api調用函數ios

1 export const getCourses = () => {
2     return $http.get('http://localhost:8080/teacher/courses')
3 }

在本例中,前端使用8081端口號,後端使用8080端口號,前端經過調用api請求數據失敗web

postman測試此api接口正常axios

如何解決同源問題?

一、在vue根目錄下新建vue.config.js文件並進行配置後端

vue.config.js文件api

 1 module.exports = {
 2     devServer: {
 3         host: 'localhost',        //主機號
 4         port: 8081,               //端口號
 5         open: true,               //自動打開瀏覽器
 6         proxy: {
 7             '/api': {
 8                 target: 'http://localhost:8080/',       //接口域名
 9                 changeOrigin: true,                     //是否跨域
10                 ws: true,                               //是否代理 websockets
11                 secure: true,                           //是否https接口
12                 pathRewrite: {                          //路徑重置
13                     '^/api': '/'
14                 }
15             }
16         }
17     }
18 };

二、修改api請求跨域

api調用函數瀏覽器

1 export const getCourses = () => {
2     return $http.get('/api/teacher/courses')
3 }

在這裏,由於vue.config.js配置了接口域名,因此此處url只須要寫餘下來的部分websocket

url徹底體

1 http://localhost:8080/teacher/courses

可是這裏由於運用到代理,因此在餘下的部分(即'/teacher/courses')前加上'/api',組成'/api/teacher/courses'

此時跨域問題解決,前端能夠從後端接口拿到數據並顯示

問題解決!

相關文章
相關標籤/搜索