4.vue引入axios同源跨域
前言:
跨域方案有很多種,既然我們用到了Vue,那麼就使用vue提供的跨域方案。
解決方案:
1.修改HttpRequestUtil.js
1 import axios from 'axios' 2 3 export var baseurl = '/api' 4 /** 5* Get請求 6*/ 7 export function get(url, callback){ 8console.log('測試get請求') 9axios.get(baseurl+url) 10.then(function (response) { 11console.log(response) 12callback(response.data,true) 13}) 14.catch(function (error) { 15console.log(error) 16callback(null,false) 17}) 18 } 19 20 21 export default { 22get 23 }
2.修改index.js
1 'use strict' 2 // Template version: 1.3.1 3 // see http://vuejs-templates.github.io/webpack for documentation. 4 5 const path = require('path') 6 7 module.exports = { 8dev: { 9 10// Paths 11assetsSubDirectory: 'static', 12assetsPublicPath: '/', 13proxyTable: { 14'/api': { 15target: 'http://127.0.0.1:8088',//設定你呼叫的介面域名和埠號 別忘了加http 16changeOrigin: true, 17pathRewrite: { 18'^/api': 'http://127.0.0.1:8088'//這裡理解成用‘/api’代替target裡面的地址,後面元件中我們掉介面時直接用api代替 比如我要呼叫'http://40.00.100.100:3002/user/add',直接寫‘/api/user/add’即可 19} 20} 21}, 22 23// Various Dev Server settings 24host: 'localhost', // can be overwritten by process.env.HOST 25port: 8090, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined 26autoOpenBrowser: false, 27errorOverlay: true, 28notifyOnErrors: true, 29poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- 30 31 32/** 33* Source Maps 34*/ 35 36// https://webpack.js.org/configuration/devtool/#development 37devtool: 'cheap-module-eval-source-map', 38 39// If you have problems debugging vue-files in devtools, 40// set this to false - it *may* help 41// https://vue-loader.vuejs.org/en/options.html#cachebusting 42cacheBusting: true, 43 44cssSourceMap: true 45}, 46 47build: { 48// Template for index.html 49index: path.resolve(__dirname, '../dist/index.html'), 50 51// Paths 52assetsRoot: path.resolve(__dirname, '../dist'), 53assetsSubDirectory: 'static', 54assetsPublicPath: '/', 55 56/** 57* Source Maps 58*/ 59 60productionSourceMap: true, 61// https://webpack.js.org/configuration/devtool/#production 62devtool: '#source-map', 63 64// Gzip off by default as many popular static hosts such as 65// Surge or Netlify already gzip all static assets for you. 66// Before setting to `true`, make sure to: 67// npm install --save-dev compression-webpack-plugin 68productionGzip: false, 69productionGzipExtensions: ['js', 'css'], 70 71// Run the build command with an extra argument to 72// View the bundle analyzer report after build finishes: 73// `npm run build --report` 74// Set to `true` or `false` to always turn it on or of 75bundleAnalyzerReport: process.env.npm_config_report 76} 77 }
proxyTable:{
'/api' :{
target: 'http://127.0.0.1:8088' ,//設定你呼叫的介面域名和埠號 別忘了加http
changeOrigin: true,
pathRewrite:{
'^/api' : 'http://127.0.0.1:8088'//這裡理解成用‘/api’代替target裡面的地址,後面元件中我們掉介面時直接用api代替 比如我要呼叫'http://40.00.100.100:3002/user/add',直接寫‘/api/user/add’即可
}
}
},