vue-cli3 跨域配置-含示例

安裝axios

在項目目錄下運行
cnpm install --save axios vue-axios

示例

以在main.js中連接後臺爲例,其他頁面在axios前加上this.即可。

1. main.js

import Vue from 'vue'			//重要!!!
import axios from 'axios'			//重要!!!
import VueAxios from 'vue-axios'		//重要!!!
import App from './App.vue'

Vue.config.productionTip = false

Vue.use(VueAxios, axios)	//重要!!!

new Vue({
  render: h => h(App),
  router
}).$mount('#app')

//************************************重要!!!
axios({	//如果是在其他頁面,使用this.axios
  method: 'post',
  url: '/api/user',			//  "/api"很重要!!!!
  data: {
    username: 'xxxxx',
    password: 'xxxxx'
  }
})
  .then(function(response) {
    alert(response)
  })
  .catch(function(error) {
    alert(error)
  })

url: '/api/user'中,/api是在vue.config.js中配置的(詳見後續),/user是接口地址,更多可參考官方文檔

2. vue.config.js

文件內容應該是這個格式:

module.exports = {
    ...
}

修改如下:

module.exports = {
devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:4000', 	//API服務器的地址
        ws: true, 				//代理websockets
        changeOrigin: true, 	// cnpm 虛擬的站點需要更管origin
        pathRewrite: {
          //重寫路徑 比如'/api/aaa/ccc'重寫爲'/aaa/ccc'
          '^/api': ''
        }
      }
    }
  }
}

個人的另一篇文章:vscode vue環境搭建+配置eslint和prettier

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章