vite+Vue3技术栈项目- 解决跨域配置代理

1. 跨域问题引入

我的前端项目启动,是 http://127.0.0.1:3000

需要访问的后端接口是:http://localhost:9693/httphwm/getList

如果直接请求,会出现跨域问题,如下:

在这里插入图片描述



2. 解决跨域编码:

  1. 在项目根目录下,创建文件 vite.config.ts,配置文件如下:

    import { defineConfig } from 'vite';
    import vue from '@vitejs/plugin-vue';
    
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [vue()],
      server: {
        port: 3000,
        open: true,
        // 配置代理
        proxy: {
          // 请求的路径前缀只要是 /testaxios 就会被拦截走这个代理
          '/testaxios': {
          /**
            *  请求的目标资源再经过替换成 /httphwm/getList 后,
            *  会加上 http://127.0.0.1:9693 这个前缀,
            *  最后请求的URL为: http://127.0.0.1:9693/httphwm/getList
            */
            target: 'http://127.0.0.1:9693',
            ws: true,
            changeOrigin: true,
            // 拦截到的请求路径 testaxios/httphwm/getList,/testaxios会被替换成空
            rewrite: (path) => path.replace(/^\/testaxios/, ''),
          },
        },
      },
    


3. 更改后端请求:

只写资源路径即可: testaxios/httphwm/getList

<template>
  <div>
    <button @click.stop="clickHandler">点击测试axios请求</button>
  </div>
</template>

<script lang="ts" setup>
  import { get } from '../../../../common/request/index';

  // 点击事件,请求接口
  const clickHandler = async () => {
    let res = await get('testaxios/httphwm/getList');
    console.log('axios请求测试', res.data);
  };
</script>


4. 编码测试OK

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ix4Z8QUP-1645525818421)(编码技术.assets/image-20220222182829942.png)]

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值