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>
相关推荐
console.log('npc')1 天前
vue3文件上传弹窗,图片pdf,word,结合预览kkview
前端·javascript·vue.js·pdf·word
inferno1 天前
CSS 基础(第二部分)
前端·css
BD_Marathon1 天前
Router_路由传参
前端·javascript·vue.js
闲云一鹤1 天前
Cesium 去掉默认瓦片和地形,解决网络不好时地图加载缓慢的问题
前端·cesium
Dreamcatcher_AC1 天前
前端面试高频13问
前端·javascript·vue.js
AI陪跑1 天前
深入剖析:GrapesJS 中 addStyle() 导致拖放失效的问题
前端·javascript·react.js
登山人在路上1 天前
Vue中导出和导入
前端·javascript·vue.js
消失的旧时光-19431 天前
Flutter 路由从 Navigator 到 go_router:嵌套路由 / 登录守卫 / 深链一次讲透
前端·javascript·网络
掘金酱1 天前
🏆2025 AI/Vibe Coding 对我的影响 | 年终技术征文
前端·人工智能·后端
成为大佬先秃头1 天前
渐进式JavaScript框架:Vue
开发语言·javascript·vue.js