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>
相关推荐
全马必破三20 分钟前
CSS 和 JS 如何阻塞浏览器渲染 DOM
javascript
c***V3231 小时前
Vue优化
前端·javascript·vue.js
努力往上爬de蜗牛2 小时前
react native真机调试
javascript·react native·react.js
李@十一₂⁰3 小时前
HTML 特殊字体符号
前端·html
y***86694 小时前
TypeScript在Electron应用中的使用
javascript·typescript·electron
小奶包他干奶奶5 小时前
Webpack学习——Loader(文件转换器)
前端·学习·webpack
zy happy6 小时前
若依 vue3 报错:找不到模块“@/api/xxxx/xxxxx”或其相应的类型声明。。Vue 3 can not find mod
前端·javascript·vue.js
潘小安6 小时前
Git Worktree + Claude Code:让你的开发效率翻倍的秘密武器
前端
meichaoWen6 小时前
【Vue3】vue3的全面学习(一)
前端·javascript·学习
小猪努力学前端7 小时前
在 React + React Router v7 SSR 项目里做多端适配,我踩的两个坑
前端·react.js