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>
相关推荐
ZC跨境爬虫2 分钟前
跟着 MDN 学 HTML day_33:(Attr 接口与属性节点的深入理解)
前端·javascript·ui·html·音视频·html5
神所夸赞的夏天16 分钟前
如何获取多层json数据,存成dictionary,并取最大最小值
java·前端·json
红色的小鳄鱼16 分钟前
前端面试js手写
开发语言·前端·javascript
焦糖玛奇朵婷20 分钟前
健身房预约小程序开发、设计
java·大数据·服务器·前端·小程序
上海云盾王帅29 分钟前
WEB业务如何接入安全防护:从零到一的实战指南
前端·安全
用户0595401744632 分钟前
AI Agent记忆丢失踩坑实录:这个问题让我排查了3天
前端·css
web行路人35 分钟前
前端对Commands(斜杠命令)一些常用
前端·javascript·vue.js·vue
当时只道寻常35 分钟前
从零到一打造企业级全栈后台管理系统 —— 技术选型、工程化实践与深度思考
前端·全栈·前端工程化
竹林81836 分钟前
用 ethers.js 连 MetaMask 做钱包登录,我踩了三个坑才搞定跨页面状态同步
前端·javascript
饺子不吃醋37 分钟前
深入理解 Vue 3 的 setup(含 Composition API)
前端·vue.js