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>
相关推荐
徐小夕3 小时前
万字拆解:零向量库、无模型微调,SAG2 凭什么刷新多跳问答 SOTA
前端·vue.js·github
黑土豆4 小时前
用 drawink 给业务页面加一层画板:从网页批注到无限板书
前端·javascript·github
恋猫de小郭4 小时前
Flutter 3.50.0 Release 的第一个崩溃,修好了,还没 hotfix
android·前端·flutter
IT_陈寒18 小时前
Redis那个过期删除策略,差点让我线上崩了
前端·人工智能·后端
jianqiang.xue18 小时前
Espressif-IDE进入维护模式:乐鑫把ESP32开发的宝押给VS Code
前端·css·ide
特创数字科技19 小时前
纯本地离线运行的文档脱敏工具(技术分享)
前端·驱动开发·python
心之语歌19 小时前
uni-app uts原生插件开发:uts 与 Kotlin 交互踩坑实录(附解决方案)
前端·后端
再吃一根胡萝卜19 小时前
DSH 插件数据链路:Host 管数据,Client 只管画
前端
feixing_fx19 小时前
CSS 变量(Custom Properties):构建可扩展的主题切换系统
前端·css·前端框架·html·css3
十有八七20 小时前
手搓 Agent(一):先有大脑——大模型只会做一件事
前端·人工智能·后端