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>
相关推荐
!win !1 小时前
前端跨标签页通信方案(下)
前端·javascript
f***45321 小时前
基于SpringBoot和PostGIS的各省与地级市空间距离分析
android·前端·后端
编码追梦人1 小时前
从 “手忙脚乱“ 到 “行云流水“:华为云 DevUI 与 MateChat 如何让前端开发飞起来
前端·华为云
用户47949283569152 小时前
TypeScript 简史:它是怎么拯救我的烂代码的
javascript·typescript
S***H2832 小时前
前端动画实现经验,性能优化与兼容性
前端
用户47949283569152 小时前
只有前端 Leader 才会告诉你:那些年踩过的模块加载失败的坑(二)
javascript
xw52 小时前
前端跨标签页通信方案(下)
前端·javascript
zzlyx993 小时前
IoTSharp前端VUE采用npm run build编译提示require() of ES Module 出错
前端·vue.js·npm
全栈技术负责人3 小时前
拒绝“无法复现”:前端全链路日志排查实战手册
前端·全链路·问题排查思路
加洛斯3 小时前
前端小知识003:JS中 == 与 === 的区别
开发语言·前端·javascript