vue_06跨域

使用yarn create vite 方式创建项目

在vite.config.ts文件中添加以下内容

  • 原始格式为
js 复制代码
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vite.dev/config/
export default defineConfig({
  plugins: [vue()]
})
  • 添加内容后
js 复制代码
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vite.dev/config/
export default defineConfig({
  plugins: [vue()],
  server:{
    proxy:{
      '/api':{
        target:'http://localhost:8000',
        changeOrigin:true,
        rewrite:(path)=>path.replace(/^\/api/,"")
      }
    }
  }
})

说明:

'/api':代理的名称,可以自己任意命名,符合规范即可,后面访问后端时,需要使用该名称

target:表示要代理的实际网址

changeOrigin:表示是否解决跨域问题

rewrite:重写path,采用正则表达式把path中的代理名,替换为空

使用代理访问后端

vue 复制代码
<template>
  <div>
    <el-button type='success' v-on:click="index">获取数据</el-button>
  </div>
</template>
<script setup lang="ts">
import axios from 'axios'
function index()
{
    console.log("我的信息");
    //'/api/index'中的 /api,就是我们在vite.config.ts文件中定义的代理名称
    axios.get("/api/index/")
    .then(res=>{
        console.log(res.data);
        
    }).catch(err=>{
        console.log(err);
        
    })
}
</script>
<style scoped>

</style>
相关推荐
用户6937175001384几秒前
2026,程序员的时代拐点到了
android·前端·后端
大龄秃头程序员4 分钟前
一次 iBeacon + BLE 无感解锁方案的实现记录
前端
小兔子18 分钟前
Python 的 GIL 与 free-threading:3.13 之后「去 GIL」走到哪一步了
前端
IT_陈寒25 分钟前
SpringBoot自动配置差点让我加班到凌晨
前端·人工智能·后端
guslegend1 小时前
脚手架原理与本地调试:从 bin 软链接到 npm link
前端·npm·node.js·脚手架·前端工程化
小宋10212 小时前
A2UI从零实战:Agent安全生成交互界面与事件回传
javascript·人工智能·安全·交互
大包子2 小时前
structuredClone vs lodash.cloneDeep:核心差异与选型指南
javascript·vue.js
海码事务所2 小时前
Google Play 新个人开发者账号上架指南:12 人连续 14 天封闭测试怎么做?
前端
田威AI2 小时前
图片内文字翻译的规格:输入输出、保真、自动化、时间与费用
前端·计算机视觉
不可能片场2 小时前
命令行中文变问号 我用环境变量救了场
前端·electron