前提:vue-cli3与vue-cli2不同的地方是,vue-cli2有config和build文件夹,但是vue-cli3没有,所以相关的配置文件要自己建
解决:
(1)在项目的根目录建vue.config.js文件,书写如下内容
module.exports = {
devServer: {
open: true, // 是否自动弹出浏览器页面
host: "localhost",
port: '8080',
proxy: {
'/api': {
target: 'http://xxxx:8000', // 请求服务器根路径
changeOrigin: true, // 是否跨域
ws: true, // websocket
pathRewrite: { // 重写路径: 当检测到请求地址里包含 /v1 时,将此路径进行跨域代理操作
'^/api': '/api'
}
}
}
}
}
(2)在main.js设置axios的默认路径
import axios from 'axios'
axios.defaults.baseURL = "http://xxxx:8000"
(3)用axios请求数据
import axios from 'axios'
export default {
data() {
return {
images: []
}
},
async created () {
await axios.get('api/v1/banners/').then(res => {
this.images = [].concat(res.data.data)
// console.log(this.images)
})
.catch(function (error) {
console.log(error.response)
})
}
}
需要注意的是url的拼接是否正确,可以通过浏览器检查来查看request的url