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>
相关推荐
小爷毛毛_卓寿杰1 分钟前
给 Embedding 模型也加一块“游乐场“—— Xinference 是怎么把 vector 变成肉眼可见的体验的
前端
忆江南4 分钟前
iOS 性能优化全面详解
前端
lichenyang4536 分钟前
HAP / HAR / HSP 到底啥区别?顺带把「导入」那点疑惑讲清楚
前端
基德爆肝c语言8 分钟前
MySQL表的操作
前端·数据库·mysql
米丘10 分钟前
SSE (server-sent events)
javascript·网络协议
秃头网友小李13 分钟前
前端难点:Element Plus 样式覆盖 —— :deep()、CSS 变量与滚动状态类名
前端·vue.js
the_answer15 分钟前
XSS 与 CSRF 深度解析
前端
打呵欠的猫23 分钟前
AI 生成的代码你敢直接上线吗?我总结出 3 条铁律
前端·ai编程
极速蜗牛26 分钟前
我在 Taro 小程序项目里实践的 API First + AI 编程方式
前端·人工智能·后端
桜吹雪31 分钟前
所有智能体架构(3):Planning(计划任务)
javascript·人工智能·langchain