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>
相关推荐
子兮曰3 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
吴仰晖3 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神3 小时前
github发布pages的几种状态记录
前端
不像程序员的程序媛5 小时前
Nginx日志切分
服务器·前端·nginx
Daniel李华5 小时前
echarts使用案例
android·javascript·echarts
北原_春希5 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
JY-HPS5 小时前
echarts天气折线图
javascript·vue.js·echarts
尽意啊5 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜5 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive5 小时前
Vue3使用ECharts
前端·javascript·echarts