Vue中网络环境配置
代理配置
vite环境中
//vite.config.js文件中 export default defineConfig({ plugins: [vue()], server: { // port:"8080", // host proxy: { '/api': { target: 'http://127.0.0.1:7001', // 代理的目标地址 rewrite: (path) => path.replace(/^\/api/, '/'), // 路径重写 changeOrigin: true, // secure: true, // target是否https接口 // ws: true, // target是否代理websockets } } } })
webpack环境
//vue.config.js文件中配置 module.exports={ lintOnSave:false, devServer:{ port:"10086", host:"localhost", proxy:{ "/":{ target:"http://127.0.0.1:7001", changeOrigin:true, pathRewrite:{"^/":""} } } } }
网络配置
//mian.js文件中配置 import axios from "axios" const app=createApp(App) axios.defaults.baseURL="http://127.0.0.1:7001/api" app.config.globalProperties.$axios=axios app.config.globalProperties.hqyj=666 app.mount('#app')
//组件.vue <script setup> import {ref,reactive,computed,onBeforeMount,getCurrentInstance,effect} from "vue" const { proxy } = getCurrentInstance();//注意在组件钩子中获取,不要在事件中 let fn=()=>{ proxy.$axios("/test") }
</script>