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>
相关推荐
u***42071 小时前
【学术会议论文投稿】Spring Boot实战:零基础打造你的Web应用新纪元
前端·spring boot·后端
v***91301 小时前
数据库高安全—openGauss安全整体架构&安全认证
android·前端·后端
VX:Fegn08951 小时前
计算机毕业设计|基于springboot+vue的健康饮食管理系统
java·vue.js·spring boot·后端·课程设计
宠..1 小时前
创建标签控件
java·服务器·开发语言·前端·c++·qt
软件技术NINI1 小时前
html css js网页制作成品——鹿晗html+css+js 4页附源码
javascript·css·html
Z_Wonderful1 小时前
主题切换(1):css变量的使用(:root)
前端·javascript·css
亮子AI1 小时前
【CSS】如何选择父级元素?
前端·css