在 IIS 上部署 Vue 项目,结果前端打包后请求 API 变成 `/api/...`,没有带上原本的后端端口。
这其实是因为:
- Vue 本地开发时用
vue.config.js/vite.config.js的proxy做了转发, - 部署到 IIS 后,IIS 并不会自动帮你转发
/api到后端端口, - 所以
/api/...会直接被当作 Vue 静态资源路径,找不到端口自然就访问失败了。
解决方案(IIS 场景)
IIS 上要做的就是 反向代理,让它把 /api 请求转发到真实后端 API 服务器的端口。
1. 安装 IIS URL Rewrite 和 Application Request Routing (ARR)
在 IIS 上做反向代理,需要两个组件:
- IIS URL Rewrite 模块
- Application Request Routing (ARR) 模块
安装后在 IIS 管理器中启用 Proxy 功能:
- 打开 IIS 管理器 → 服务器节点 →
Application Request Routing Cache - 点击右边 Server Proxy Settings → 勾选 Enable Proxy → 应用。
2. 在 Vue 部署目录下加 web.config
假设你的后端 API 运行在 http://localhost:5000,那么可以在 Vue 的 dist 目录下创建或修改 web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<!-- Vue 前端 history 模式路由支持 -->
<rewrite>
<rules>
<!-- API 请求转发到后端 -->
<rule name="API Reverse Proxy" stopProcessing="true">
<match url="^api/(.*)" />
<action type="Rewrite" url="http://localhost:5000/api/{R:1}" />
</rule>
<!-- 前端 history 模式路由回退到 index.html -->
<rule name="VueRouter" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
3. 前端请求方式
你的前端 axios / fetch 里仍然可以写:
axios.get('/api/users')
这样:
- 开发环境走本地代理(
vue.config.js/vite.config.js里设置的) - 生产环境(IIS)走
web.config反向代理,把/api转到localhost:5000
4. 如果不想用反向代理
也可以在 .env.production 写完整 URL:
VITE_API_BASE_URL=http://yourserver.com:5000
但这样要处理跨域(后端加 CORS 头)。

浙公网安备 33010602011771号