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>
相关推荐
DC...21 分钟前
vue滑块组件设计与实现
前端·javascript·vue.js
Mars狐狸30 分钟前
AI项目改用服务端组件实现对话?包体积减小50%!
前端·react.js
H5开发新纪元39 分钟前
Vite 项目打包分析完整指南:从配置到优化
前端·vue.js
嘻嘻嘻嘻嘻嘻ys40 分钟前
《Vue 3.3响应式革新与TypeScript高效开发实战指南》
前端·后端
恋猫de小郭1 小时前
腾讯 Kuikly 正式开源,了解一下这个基于 Kotlin 的全平台框架
android·前端·ios
2301_799404911 小时前
如何修改npm的全局安装路径?
前端·npm·node.js
(❁´◡双辞`❁)*✲゚*1 小时前
node入门和npm
前端·npm·node.js
韩明君1 小时前
前端学习笔记(四)自定义组件控制自己的css
前端·笔记·学习
tianchang1 小时前
TS入门教程
前端·typescript
吃瓜群众i1 小时前
初识javascript
前端