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>
相关推荐
程序猿阿伟2 分钟前
《声音的变形记:Web Audio API的实时特效法则》
开发语言·前端·php
凌览6 分钟前
有了 25k Star 的MediaCrawler爬虫库加持,三分钟搞定某红书、某音等平台爬取!
前端·后端·python
万少8 分钟前
2-自然壁纸实战教程-AGC 新建项目
前端·harmonyos
满分观察网友z19 分钟前
别小看这个滑动条!从性能灾难到用户挚爱的 uni-app Slider 踩坑实录
前端
满分观察网友z22 分钟前
别再裸写<textarea>了!一个“小”功能,我用上了它几乎所有API
前端
bemyrunningdog23 分钟前
二进制权限控制方案
javascript·react.js·ecmascript
西西木科技丨Shopify开发机构28 分钟前
如何在 Shopify 中建立重定向
前端·html
汪子熙34 分钟前
深入探析 header facets:定位与应用
前端·javascript
你听得到1135 分钟前
从需求到封装:手把手带你打造一个高复用、可定制的Flutter日期选择器
前端·flutter
江城开朗的豌豆40 分钟前
Vue Router vs location.href:导航跳转的正确姿势,你选对了吗?
前端·javascript·vue.js