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

部署Rails 7 API+Vite React前端到Heroku后路由组件无法渲染求助

Rails 7 API + Vite React 部署Heroku后React Router路由失效及Vite配置路径问题解决思路

一、先修复Vite配置文件路径不匹配问题

Heroku日志提示找不到/app/frontend/vite.config.js,但实际文件在项目根目录的/frontend文件夹下,问题出在Node.js buildpack的执行上下文或配置指向错误:

  • 在项目根目录创建/修改package.json,指定build阶段进入frontend目录执行命令:
    {
      "scripts": {
        "heroku-prebuild": "cd frontend && npm install",
        "heroku-build": "cd frontend && npm run build"
      }
    }
    
  • 检查vite.json配置:如果未使用vite_ruby插件,直接删除该文件即可;如果依赖该插件,确认sourceCodeDir值与实际目录一致(当前"sourceCodeDir": "frontend"是正确的)。

二、修复React Router客户端路由的Nginx配置问题

当前Nginx配置把所有请求都代理到Rails后端,但客户端路由需要Nginx在匹配不到静态文件时返回index.html,修改nginx.conf.erb如下:

daemon off;
worker_processes <%= ENV['NGINX_WORKERS'] || 4 %>;

events {
    use epoll;
    accept_mutex on;
    worker_connections <%= ENV['NGINX_WORKER_CONNECTIONS'] || 1024 %>;
}

http {
    gzip on;
    gzip_comp_level 2;
    gzip_min_length 512;
    gzip_proxied any;

    server_tokens off;

    log_format l2met 'measure#nginx.service=$request_time request_id=$http_x_request_id';
    access_log <%= ENV['NGINX_ACCESS_LOG_PATH'] || 'logs/nginx/access.log' %> l2met;
    error_log <%= ENV['NGINX_ERROR_LOG_PATH'] || 'logs/nginx/error.log' %>;

    include mime.types;
    default_type application/octet-stream;
    sendfile on;

    client_body_timeout 5;

    upstream app_server {
        server unix:/tmp/nginx.socket fail_timeout=0;
    }

    server {
        listen <%= ENV["PORT"] %>;
        server_name _;
        keepalive_timeout 5;

        # 指向Vite构建后的静态文件目录
        root /app/frontend/dist;

        # API请求转发到Rails后端
        location /api {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_pass http://app_server;
        }

        # 静态文件优先匹配,匹配失败返回index.html,交给React Router处理
        location / {
            try_files $uri $uri/ /index.html;
            # 可选:强制HTTPS
            # if ($http_x_forwarded_proto != "https") {
            #   return 301 https://$host$request_uri;
            # }
        }
    }
}

核心调整:

  • 用root指定Vite构建产物目录
  • 拆分API请求和前端路由请求,API转发到Rails,其余请求优先返回静态文件,失败则返回index.html

三、Buildpack配置与部署流程检查

  • 严格按顺序设置Buildpack:必须是 heroku/nodejs → heroku/ruby → https://github.com/heroku/heroku-buildpack-nginx.git,确保前端先构建,再处理Rails,最后启动Nginx
  • 设置生产环境变量:
    heroku config:set NODE_ENV=production
    
  • 验证构建产物:部署后通过heroku run bash进入容器,检查/app/frontend/dist目录是否存在index.html及静态资源,确认构建命令执行成功

四、Vite配置优化

修改vite.config.js,区分开发/生产环境配置,避免生产环境无用的代理设置:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig(({ mode }) => {
  const config = { plugins: [react()] };

  // 仅开发环境启用API代理
  if (mode === 'development') {
    config.server = {
      proxy: {
        '/api': {
          target: 'http://localhost:3000',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    };
  }

  return config;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 21:57:10