一、修改vue.config.js文件
1.注意
1.1.该文件不影响打包后的文件,即这里设置的跨域,在打包后部署的文件中还需要重新解决跨域问题
2.代码详解
module.exports = {
configureWebpack:{
resolve:{
//下面的alias可以做到为目录起别名,优化代码路径
alias:{
'components':'@/components',
'network':'@/network',
'views':'@/views'
}
}
},
outputDir: 'dist', //build输出目录
assetsDir: 'assets', //静态资源目录(js, css, img)
lintOnSave: false, //是否开启eslint
devServer: {
open: true, //是否自动弹出浏览器页面
host: "localhost",
port: '80',
https: false, //是否使用https协议
hotOnly: true, //是否开启热更新
//设置代理,解决跨域问题的关键
proxy: {
'/api': {
target: 'https://music.163.com/api/', //API服务器的地址
changeOrigin: true,
pathRewrite: {
'^/api': ''
},
// 突破host和origin的限制
headers: {
referer: 'http://music.163.com',
origin: 'http://music.163.com',
host: 'music.163.com'
}
},
},
},
//不同的模式做到一些处理
chainWebpack: config => {
// 发布模式
config.when(process.env.NODE_ENV === 'production', config => {
config.entry('app').clear().add('./src/main-prod.js')
config.set('externals', {
vue: 'Vue',
'vue-router': 'VueRouter',
axios: 'axios',
lodash: '_',
echarts: 'echarts',
nprogress: 'NProgress',
'vue-quill-editor': 'VueQuillEditor'
})
config.plugin('html').tap(args => {
args[0].isProd = true
return args
})
})
// 开发模式
config.when(process.env.NODE_ENV === 'development', config => {
config.entry('app').clear().add('./src/main-dev.js')
config.plugin('html').tap(args => {
args[0].isProd = false
return args
})
})
}
}
3.需加内容
3.1.在vue.config.js文件中把这几处地址改为api所在服务器地址
注意:
- pathRewrite可以重写路径 ;
- 在前端调试的位置显示接口调用地址不是真正的接口调用地址,真正调用的地址是target的地址,前面的’/‘只是一个假的路径(可以随意写)
- 当服务端接口地址发生改变,只需要把此处的路径修改为服务端api的路径即可
- 项目部署时需重新解决跨域问题,使用nginx进行代理可以解决跨域
3.2.在接口调用模块设置baseURL为 ”/“