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>
相关推荐
东东5161 小时前
基于ssm的网上房屋中介管理系统vue
前端·javascript·vue.js
harrain2 小时前
什么!vue3.4开始,v-model不能用在prop上
前端·javascript·vue.js
阿蒙Amon7 小时前
TypeScript学习-第7章:泛型(Generic)
javascript·学习·typescript
睡美人的小仙女1278 小时前
Threejs加载环境贴图报错Bad File Format: bad initial token
开发语言·javascript·redis
fanruitian8 小时前
uniapp android开发 测试板本与发行版本
前端·javascript·uni-app
rayufo8 小时前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
RANCE_atttackkk8 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
摘星编程9 小时前
React Native + OpenHarmony:Timeline垂直时间轴
javascript·react native·react.js
2501_944525549 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 支出分析页面
android·开发语言·前端·javascript·flutter
jin12332210 小时前
React Native鸿蒙跨平台完成剧本杀组队详情页面,可以复用桌游、团建、赛事等各类组队详情页开发
javascript·react native·react.js·ecmascript·harmonyos