vite中配置服务代理

前言

在vite中配置服务代理和webpack中大差不差,不过有些写法会有些不同

具体配置:配置 Vite {#configuring-vite} | Vite中文网

这里我写了一个demo,如下所示

开启node服务

我用express启动了一个服务,分别暴露两个接口

进行相关配置

在vite.config.ts文件中进行配置

javascript 复制代码
export default defineConfig({
  server:{
    // cors: true, // 默认启用并允许任何源
    open: true, // 在服务器启动时自动在浏览器中打开应用程序
    proxy:{
      '/api':{
        target:'http://localhost:3030/api',
        changeOrigin:true,
        rewrite:(path)=>path.replace(/^\/api/,'')
      },
      '/newApi':{
        target:'http://localhost:3030/newApi',
        changeOrigin:true,
        rewrite:(path)=>path.replace(/^\/newApi/,'')
      }
    }
  }
})

请求测试

html 复制代码
<template>
    <el-button @click="testApi1">请求接口1</el-button>
    <el-button @click="testApi2">请求接口2</el-button>
</template>
<script lang="ts" setup>
import request from 'axios'
 const requestUrl1:string = '/api'
 const requestUrl2:string = '/newApi'
 const testApi1 = ()=>{
   request.get(`${requestUrl1}/test`).then((res:any)=>{
    console.log(res,'/api/test的请求结果')
   })
 }
 const testApi2 = ()=>{
   request.get(`${requestUrl2}/test`).then((res:any)=>{
    console.log(res,'/newApi/test的请求结果')
   })
 }
</script>
<style lang="less" scoped>

</style>
相关推荐
LaiYoung_几秒前
🎁 送你一套超好用超实用的 FE AI-Coding Skills
前端·人工智能·开源
幼儿园技术家19 分钟前
实现 GEO 监控:从多引擎探测到优化闭环
前端·后端
甲维斯19 分钟前
GLM5.2+ZCode复刻坦克大战,自测50万帧!
前端·ai编程·游戏开发
Csvn1 小时前
useRef 的 5 个冷门但救命的高级用法
前端
小小小小宇1 小时前
Harness Engineering 与 AI 联动
前端
鱼人1 小时前
HTML5 页面性能优化大全
前端
ping某1 小时前
专栏-null 和 undefined 到底是什么?
前端·javascript·后端
用户900463370401 小时前
5MB vs 4KB vs 无限大:浏览器存储谁更强?
前端
小小小小宇2 小时前
Harness Engineering 全解析与应用
前端
牧艺2 小时前
cos-design v3.0:从 15 个 Demo 到 49 个组件的视觉特效库
前端·视觉设计