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>
相关推荐
亿元程序员几秒前
祖传项目二开快上线了,却还有很多旧的资源,怎么办?
前端
GIS学姐嘉欣3 分钟前
0帧起手《Vue零基础教程》,从前端框架到GIS开发
前端·vue.js·前端框架·gis
你说啥名字好呢3 分钟前
【React中的闭包陷阱】
javascript·react.js·ecmascript
麦麦在写代码6 分钟前
前端学习6(JS 1)
前端·javascript·学习
沈询-阿里13 分钟前
AI Agent系列 - 1 什么是 ReAct Agent?
开发语言·javascript·ecmascript
白帽子黑客杰哥15 分钟前
CTF Web题目常用考点与解题技巧合集
前端·数据库·web安全·网络安全·ctf·信息收集
许___17 分钟前
axios使用 CancelToken / AbortController 方法进行取消请求
前端·javascript
LYFlied22 分钟前
Webpack详细打包流程解析
前端·面试·webpack·node.js·打包·工程化
明朝百晓生25 分钟前
强化学习[page14]【chapter7】Temporal-Difference Learning (TD learning)
前端·html