1、main.js导入axios
在main.js加入下面三句
import axios from 'axios'
axios.defaults.baseURL = "/api";//api用于后面跨域前缀
app.provide('$axios', axios);
2、vue.config.js配置
这里可以参考vue3:axios跨域请求问题
module.exports = {
configureWebpack: {
resolve: {
// 给路径起别名
alias: {
'assets': '@/assets',
'common': '@/common',
'components': '@/components',
'network': '@/network',
'views': '@/views'
}
}
},
devServer: {
proxy: {
'/api': {
// 跨域的服务器地址
target: 'https://4f80-218-70-255-98.jp.ngrok.io',
// 是否允许跨域
changeOrigin: true,
pathRewrite: {
'^/api': ""
}
},
}
}
}
3、使用
每次使用前需要导入,但是应该可以全局导入?萌新不清楚这个。
import { inject } from 'vue'
const $axios = inject('$axios')
$axios.post('/post', formData).then(res => {
console.log(res);
console.log('success');
}, err => {
// error callback
console.log(err);
console.log('error');
});