You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Web App部署React+Node.js应用后API路由无法访问求助

解决Azure Web App中React+Node.js应用API路由404问题

可能的原因及解决方案

1. 配置正确的启动命令

Azure Web App默认不会自动启动Node.js服务,需手动指定:

  • 登录Azure门户进入你的Web App
  • 导航到配置 > 常规设置
  • 在启动命令中填入node index.js(若入口文件为根目录下的index.js)
  • 保存配置并重启Web App

2. 修正web.config的重写规则

当前配置仅排除/api路由不被重写到React根路径,但未将API请求转发给Node服务,替换为以下配置:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <!-- 注册iisnode处理Node.js请求 -->
      <add name="iisnode" path="index.js" verb="*" modules="iisnode"/>
    </handlers>
    <rewrite>
      <rules>
        <!-- 优先处理API路由,转发到Node服务 -->
        <rule name="API Routes" stopProcessing="true">
          <match url="^api/(.*)$" />
          <action type="Rewrite" url="index.js/{R:1}" />
        </rule>
        <!-- 处理React单页应用路由 -->
        <rule name="React Routes" 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="/" />
        </rule>
      </rules>
    </rewrite>
    <!-- 可选:启用日志便于排查问题 -->
    <iisnode loggingEnabled="true" logDirectory="iisnode"/>
  </system.webServer>
</configuration>

3. 匹配本地与Azure的Node.js版本

版本不兼容可能导致路由加载异常:

  • 在Azure门户配置 > 常规设置中,设置Node.js版本与本地开发环境一致
  • 保存后重启Web App

4. 验证部署后的文件结构

使用Kudu工具(访问https://<你的应用名称>.scm.azurewebsites.net/)查看site/wwwroot目录:

  • 确认index.js存在于根目录
  • 确认build/routes文件夹及路由文件存在,路径与代码引用一致

5. 调整CORS配置

本地环境CORS默认允许所有请求,Azure上需更严格配置:

  • 修改Node.js代码中的CORS设置:
    app.use(cors({ origin: process.env.CLIENT_ORIGIN }));
    
  • 在Azure门户配置 > 应用设置中,添加CLIENT_ORIGIN变量,值为你的前端应用域名(例如https://<your-app-name>.azurewebsites.net)
  • 重启Web App

内容的提问来源于stack exchange,提问作者Ivan Bonilla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 11:50:02