前言:
跨域方案有很多种,既然我们用到了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){8 console.log('测试get请求')9 axios.get(baseurl+url)10 .then(function (response) {11 console.log(response)12 callback(response.data,true)13 })14 .catch(function (error) {15 console.log(error)16 callback(null,false)17 })18 }19 20 21 export default {22 get23 }复制代码
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 = { 8 dev: { 9 10 // Paths11 assetsSubDirectory: 'static',12 assetsPublicPath: '/',13 proxyTable: {14 '/api': {15 target: 'http://127.0.0.1:8088',//设置你调用的接口域名和端口号 别忘了加http16 changeOrigin: true,17 pathRewrite: {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 settings24 host: 'localhost', // can be overwritten by process.env.HOST25 port: 8090, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined26 autoOpenBrowser: false,27 errorOverlay: true,28 notifyOnErrors: true,29 poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-30 31 32 /**33 * Source Maps34 */35 36 // https://webpack.js.org/configuration/devtool/#development37 devtool: 'cheap-module-eval-source-map',38 39 // If you have problems debugging vue-files in devtools,40 // set this to false - it *may* help41 // https://vue-loader.vuejs.org/en/options.html#cachebusting42 cacheBusting: true,43 44 cssSourceMap: true45 },46 47 build: {48 // Template for index.html49 index: path.resolve(__dirname, '../dist/index.html'),50 51 // Paths52 assetsRoot: path.resolve(__dirname, '../dist'),53 assetsSubDirectory: 'static',54 assetsPublicPath: '/',55 56 /**57 * Source Maps58 */59 60 productionSourceMap: true,61 // https://webpack.js.org/configuration/devtool/#production62 devtool: '#source-map',63 64 // Gzip off by default as many popular static hosts such as65 // 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-plugin68 productionGzip: false,69 productionGzipExtensions: ['js', 'css'],70 71 // Run the build command with an extra argument to72 // 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 of75 bundleAnalyzerReport: process.env.npm_config_report76 }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’即可 } } }复制代码
发现文章中的错误,或者有更好的建议,欢迎评论或进前端全栈群:866109386,来交流讨论吹水。