在网上查了很多资料,基本上都不全,自己在总结一下,留着以后备用。
1.首先在项目中新建一个vue.config.js文件,在文件中配置如下:
//vue.config.js
module.exports = {
devServer: {
open: true, //是否自动弹出浏览器页面
// host: "localhost",
// port: '8080',
proxy: { //配置跨域,可以配置多个跨域
'/api': {
target: 'http://121.121.67.254:8185/', //这里后台的地址模拟的;应该填写你们真实的后台接口
changOrigin: true, //允许跨域
pathRewrite: {
/* 重写路径,当我们在浏览器中看到请求的地址为:http://localhost:8080/api/core/getData/userInfo 时
实际上访问的地址是:http://121.121.67.254:8185/core/getData/userInfo,因为重写了 /api
*/
'^/api': ''
}
},
}
},
}
2.在main.js文件中导入axios,如果没有,安装npm install axios
//main.js
import axios from 'axios'
Vue.prototype.$axios = axios
3.在页面中使用,接口前放了一个‘/api’,就是使用上面定义的跨域,
//xxx.js
this.$axios.post('/api/ch05/index', form).then(res => {
console.log(res)
if (res.data !== 'success') {
this.$refs.uploadExcel.loading = false
this.$Message.error("导入失败!");
}
this.$refs.uploadExcel.loading = false
this.$message.success('文件上传成功!')
})