25_配置代理

本文介绍了两种在Vue项目中配置代理以解决跨域问题的方法。第一种是在vue.config.js中直接设置代理,第二种是通过定义多个路径前缀进行不同目标地址的代理。示例代码展示了如何配置代理到不同端口,并在App.vue组件中调用axios获取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值