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

Create React App部署Platform.sh后代理中间件失效(405错误)

问题分析

你遇到的核心问题是:Create React App(CRA)的自定义代理中间件(src/proxy.ts)仅在开发环境生效。本地开发时,CRA的start命令会启动Node.js开发服务器,加载并执行这个代理逻辑;但部署到Platform.sh后,你部署的是CRA构建后的纯静态文件,没有Node.js服务器运行,代理规则完全不生效,静态服务器收到/api路径的请求时,因无法处理对应HTTP方法(比如POST)返回405错误。

解决方案

根据Platform.sh的部署特性,推荐两种解决方式:

方案一:通过Platform.sh路由配置直接代理(推荐)

利用Platform.sh的路由层直接配置反向代理,无需修改前端代码,性能更优。

  1. 在项目根目录创建/编辑.platform/routes.yaml文件,添加以下规则:
# 代理所有/api开头的请求到目标API
"https://{default}/api":
  type: proxy
  url: "https://api.mews-demo.com/"

# 静态站点的默认路由
"https://{default}/":
  type: upstream
  upstream: "app:http"
  1. 确保你的.platform.app.yaml已正确配置静态站点服务,示例:
name: app
type: nodejs:18

hooks:
  build: |
    npm install
    npm run build

web:
  locations:
    "/":
      root: "build"
      passthru: false
      allow: true
  1. 提交代码并重新部署到Platform.sh,路由代理会自动生效。

方案二:添加生产环境Node.js服务器托管静态文件+代理

如果需要更复杂的代理逻辑(比如自定义请求拦截),可以在生产环境启动Node.js服务器,同时托管静态文件和处理代理。

  1. 安装依赖:
npm install express http-proxy-middleware --save
  1. 在项目根目录创建server.js文件:
const express = require('express');
const path = require('path');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

// 配置代理规则,和本地逻辑一致
app.use('/api', createProxyMiddleware({
  target: 'https://api.mews-demo.com',
  changeOrigin: true,
  pathRewrite: {
    '^/api': '',
  },
}));

// 托管CRA构建后的静态文件
app.use(express.static(path.join(__dirname, 'build')));

// SPA路由兼容:所有非API请求返回index.html
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

// 启动服务器,使用Platform.sh提供的端口环境变量
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
  1. 修改package.json的scripts:
{
  "scripts": {
    "start": "react-scripts start", // 开发环境保留原命令
    "build": "react-scripts build",
    "start:prod": "node server.js" // 新增生产环境启动命令
  }
}
  1. 更新.platform.app.yaml的启动命令:
web:
  commands:
    start: npm run start:prod
  1. 本地测试:运行npm run build && npm run start:prod,验证代理正常工作后再部署到Platform.sh。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:25:35