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>