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>
相关推荐
无羡仙3 分钟前
AI终于‘看见’网页了!Stagewise让UI修改从‘盲调’变‘指哪打哪
前端
柯腾啊1 小时前
“Script error.”的产生原因和解决办法
前端·javascript·浏览器
沙漠之皇1 小时前
ts 定义重复对象字段
前端
HashTang2 小时前
不用再配服务器了!这套 Next.js + Cloudflare 模板,一个人搞定全栈出海
前端·后端·边缘计算
Cory.眼2 小时前
WebRTC入门指南:实时通信零基础
javascript·webrtc·实时通信
前端架构师-老李2 小时前
16 Electron 应用自动更新方案:electron-updater 完整指南
前端·javascript·electron
一只学java的小汉堡2 小时前
HTML 01入门:从概念到开发环境搭建与页面头部配置
前端·css·html
拖拉斯旋风2 小时前
📚 JavaScript 变量声明三剑客:`var`、`let`、`const` 学习笔记
javascript
用户21496515898753 小时前
从零搭建uniapp环境-记录
前端
可触的未来,发芽的智生4 小时前
追根索源:换不同的词嵌入(词向量生成方式不同,但词与词关系接近),会出现什么结果?
javascript·人工智能·python·神经网络·自然语言处理