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

如何在Vercel上无需/api路径用Node运行React构建并集成prerender.io

Vercel部署React应用:通过Node服务器运行构建产物(无需/api路径)

问题核心

Vercel默认会优先托管React的build静态文件夹,根目录的server.js不会自动作为请求入口;而放入api目录虽能运行Node服务,但会强制带上/api前缀。以下是两种可行的解决方式:


方法1:Serverless Functions自定义路由(推荐)

利用Vercel的Serverless Functions机制,通过路由重写隐藏/api前缀:

  1. 调整项目结构与代码

    • 在项目根目录创建api文件夹,新建index.js,将原server.js内容迁移并修改为Vercel兼容的格式:
      const express = require('express');
      const prerender = require('prerender-node');
      const path = require('path');
      const serverless = require('serverless-http');
      
      const app = express();
      
      // 托管build静态文件
      app.use(express.static(path.join(__dirname, '../build')));
      
      // 配置prerender.io
      app.use(prerender.set('prerenderToken', 'MY TOKEN'));
      
      // 所有路由返回React入口文件
      app.get('*', (req, res) => {
        res.sendFile(path.join(__dirname, '../build', 'index.html'));
      });
      
      // 导出Serverless handler
      module.exports.handler = serverless(app);
      
  2. 安装依赖

    npm install serverless-http --save
    
  3. 修改vercel.json
    通过路由重写,让所有请求指向api/index.js但隐藏前缀:

    {
      "rewrites": [
        { "source": "/(.*)", "destination": "/api/index.js" }
      ]
    }
    

方法2:配置为标准Node.js服务器项目

让Vercel直接将根目录的server.js作为服务器入口,而非静态托管:

  1. 修复server.js的缺失依赖与导出
    原代码缺少path模块引入,且需导出app供Vercel使用:

    const express = require('express');
    const prerender = require('prerender-node');
    const path = require('path'); // 新增:引入path模块
    
    const app = express();
    
    // 托管build静态文件
    app.use(express.static('build'));
    
    // 配置prerender.io
    app.use(prerender.set('prerenderToken', 'MY TOKEN'));
    
    // 所有路由返回React入口文件
    app.get('*', (req, res) => {
      res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
    });
    
    // 本地开发启动服务器(生产环境由Vercel处理端口)
    const port = process.env.PORT || 3000;
    if (process.env.NODE_ENV !== 'production') {
      app.listen(port, () => {
        console.log(`Server running on port ${port}`);
      });
    }
    
    // 导出app供Vercel使用
    module.exports = app;
    
  2. 修改vercel.json
    指定构建命令与服务器运行配置,禁用静态资源优先托管:

    {
      "buildCommand": "npm run build",
      "devCommand": "npm run start",
      "installCommand": "npm install",
      "functions": {
        "server.js": {
          "runtime": "@vercel/node@20"
        }
      },
      "rewrites": [
        { "source": "/(.*)", "destination": "/server.js" }
      ]
    }
    

通用注意事项

  • 确保已安装prerender-node依赖:npm install prerender-node --save
  • 本地测试先执行npm run build生成静态文件,再用npm start启动服务器验证功能
  • Vercel部署时会自动执行buildCommand生成build文件夹,再启动服务器

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 01:22:47