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)]

Logo

前往低代码交流专区

更多推荐