在vue项目内的vue.config.js文件中
module.exports内找devServer,如果没有手动添加。
代码:
module.exports = {
devServer: {
host:"localhost",
port:8080,
proxy: {
"/api": { //自定义
"target": "https://localhost:5001", //这里可以跟随项目实际部署服务器来
ws: true,
secure: false,// 这个跨https时一定要加
changeOrigin: true,
pathRewrite: {
"^/api": "/api"//自定义
}
}
}
}
}
我的后台服务启动:https://localhost:5001/api/user
前台启动后:http://localhost:8080/#/myDemo
在我的myDemo页面import了axios
<script>
import axios from 'axios'
export default {
name: 'myDemo',
data(){
return {
myTest: null
}
},
methods: {
getMyTest() {
axios.get('/api/user')
.then((res) => {
this.myTest = res.data.datas;
console.log(res)
})
.catch((err) => {
console.log(err)
})
}
},
mounted() {
this.getMyTest();
}
}
</script>
axios想使用需要敲命令引到项目中,在项目根目录下敲以下
npm install --save axios
鸣谢文章:vue——前端跨域