config -》index.js
dev:{
env: require('./dev.env'),
port: process.env.PORT || 8081,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://suneee.dcp.weilian.cn/',//設定你調用的接口域名和端口号 别忘了加http
changeOrigin: true,
pathRewrite: {
'^/api': '/'//這裡了解成用‘/api’代替target裡面的位址,後面元件中我們掉接口時直接用api代替 比如我要調用'http://40.00.100.100:3002/user/add',直接寫‘/api/user/add’即可
}
},//可以配置多個代理 設定同上
},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
這裡跨域就解決了
使用eg:
.get("/api/接口")
詳細步驟:
由于vue-resourece官方停止維護,是以轉向了axios,github上一萬三千多的star, 足以證明其強大。 一個登入的場景,用axios發送post請求去登入,能成功傳回資料,但是用作權限驗證的cookie就是沒有儲存,經查閱,axios 預設不發送cookie,跨域也是一個原因,需要全局設定
axios.defaults.withCredentials = true
相關閱讀:withCredentials
将axios發送的資料格式轉換為form-data格式
//npm install axios的時候預設會安裝qs
// qs相關的問題請搜尋"nodejs qs"或者看這裡https://www.npmjs.com/package/qs
import qs from 'qs';
// 将請求資料轉換為form-data格式
// 這裡不用qs,用FormData也可以,不贅述
var data = qs.stringify({
currentPage: "0",
pageSize: "10",
type: "1",
});
axios.post('/url', data)
.then(function (response) {
//
})
.catch(function (error) {
//
});
Vue-cli proxyTable 解決開發環境的跨域問題
相關閱讀: API proxy
http-proxy-middleware
package
在vue-cli的config檔案index.js裡有一個參數叫proxyTable
proxyTable: {
'/list': {
target: 'http://api.xxxxxxxx.com',
changeOrigin: true,
pathRewrite: {
'^/list': '/list'
}
}
}
這樣我們在寫url的時候,隻用寫成/list/1就可以代表api.xxxxxxxx.com/list/1.
那麼又是如何解決跨域問題的呢?其實在上面的'list'的參數裡有一個changeOrigin參數,接收一個布爾值,如果設定為true,那麼本地會虛拟一個服務端接收你的請求并代你發送該請求,這樣就不會有跨域問題了,當然這隻适用于開發環境。增加的代碼如上所示