25_配置代理
第一种 (有瑕疵)
npm i axios
App.vue
<template>
<div>
<button @click="getStudents">获取学生信息</button>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "App",
methods: {
getStudents() {
axios.get("http://localhost:8080/students").then(
(response) => {
console.log("请求成功", response.data);
},
(error) => {
console.log("请求失败", error.message);
}
);
},
},
};
</script>
vue.config.js
const { defineConfig } = require("@vue/cli-service");
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false, //关闭语法检查
devServer: {
//开启代理服务器
proxy: "http://localhost:5000",
},
});

第二种
vue.config.js
const { defineConfig } = require("@vue/cli-service");
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false, //关闭语法检查
//方式一
// devServer: {
// //开启代理服务器
// proxy: "http://localhost:5000",
// },
//方式二
devServer:{
proxy:{
//前缀
'/atguigu':{
target:'http://localhost:5000',
pathRewrite:{'^/atguigu':''},
//ws和changeOrigin 不写默认都是true
// ws:true, //用于支持websocket
// changeOrigin:true //用于控制请求头中的host值m
},
'/demo':{
target:'http://localhost:5001',
pathRewrite:{'^/demo':''},
}
}
}
});
App.vue
<template>
<div>
<button @click="getStudents">获取学生信息</button>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "App",
methods: {
getStudents() {
axios.get("http://localhost:8080/atguigu/students").then(
(response) => {
console.log("请求成功", response.data);
},
(error) => {
console.log("请求失败", error.message);
}
);
},
},
};
</script>
本文介绍了两种在Vue项目中配置代理以解决跨域问题的方法。第一种是在vue.config.js中直接设置代理,第二种是通过定义多个路径前缀进行不同目标地址的代理。示例代码展示了如何配置代理到不同端口,并在App.vue组件中调用axios获取数据。
1万+

被折叠的 条评论
为什么被折叠?



