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>
相关推荐
何何____7 分钟前
TypeScript 函数类型兼容性
前端·javascript·typescript
雪芽蓝域zzs18 分钟前
json数据转化成interface属性
前端·javascript·json
Java小卷21 分钟前
Vue3 动态表单支持弹框组件
前端·vue.js·低代码
溪语流沙32 分钟前
【Web全栈进阶】前端对接新契约:信封解包 + 统一错误处理
前端·vue.js·python·状态模式·fastapi
国服第二切图仔1 小时前
Chrome 插件开发实战指南:从入门到发布
前端·chrome
鬼手点金1 小时前
ReAct 循环
linux·服务器·前端·javascript·react.js·前端框架
鬼手点金1 小时前
上下文:Agent 的眼睛
java·前端·人工智能·git·深度学习
雪芽蓝域zzs1 小时前
Vue导入方法三种方式对比
前端·javascript·vue.js
定栓2 小时前
Webpack迁到Vite第八节:错误排查实录
前端·webpack·devops