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>
相关推荐
玖玖passion20 分钟前
React 常用 Hooks 函数及使用方法完全指南(useState / useEffect / useRef / useContext / useCallback / useMemo / useReducer)
前端·javascript
Awu122725 分钟前
⚡精通Claude第6课-Hooks钩子系统:从前端视角玩转AI自动化工作流
前端·aigc·claude
椰猫子26 分钟前
Spring Framework(Bean)
java·前端·spring
道清茗27 分钟前
【RH294知识点汇总】第 7 章 《 使用角色和 Ansible 内容集合简化 Playbook 》
java·前端·ansible
TechMasterPlus33 分钟前
Hermes 深度解析:React Native 高性能 JavaScript 引擎实践指南
javascript·react native·react.js
前端那点事35 分钟前
彻底弄懂async/await!解决回调地狱,Vue异步开发必备(超全实战)
前端·vue.js
VagueVibes42 分钟前
Openclaw 快速接入 DeepSeek V4 Pro 指南
javascript
A_nanda1 小时前
VS2022安装QT6.5.3后,如何更新项目配置
前端·javascript·vue.js
ZC跨境爬虫1 小时前
UI前端美化技能提升日志day8:(Watch专区字体优化+尺寸校准+视觉重构+结构分层)
前端·ui·重构·html
heyCHEEMS1 小时前
记录一下自动化构建中 SSE 与子进程管理的三个坑
javascript·node.js