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>
相关推荐
林小帅23 分钟前
NestJS v11 + Prisma v7 ESM 迁移配置解析
前端·javascript·后端
IT_陈寒39 分钟前
React的setState竟然不是立刻生效的,害我调试半天
前端·人工智能·后端
简简单单就是我_hehe42 分钟前
前端埋点日志解决方案:完整 User-Agent 解析工具实现,爬虫识别、设备品牌、操作系统、浏览器版本全解析(附完整源码)
前端·爬虫
William_Xu2 小时前
Vue 2 与 Vue 3 生命周期对比
前端
Hilaku2 小时前
为什么你的大文件断点续传,一遇到弱网就崩溃?
前端·javascript·程序员
胡哈3 小时前
React Compiler:让开发者忘掉 memo 这件事
前端·react.js
xiyueyezibile3 小时前
“自迭代” Skill 的 team-pitfalls 的演进
前端·后端·ai编程
林恒smileZAZ3 小时前
`Array(100).map(() => 1)` 为什么全为空?
前端·javascript
小巧的砖头3 小时前
C#会重蹈覆辙吗?系列之2:反射及元数据的性能问题
开发语言·前端·c#
KaMeidebaby3 小时前
卡梅德生物技术快报|蛋白的叠氮基修饰:实操解析:核酸模板耦合蛋白的叠氮基修饰实现靶蛋白定点共价标记
前端·人工智能·物联网·算法·百度