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

部署在Render的MERN应用本地运行失败,报500及代理错误

本地MERN应用Vite代理/graphql触发AggregateError,部署环境正常

数月前开发的MERN应用在Render部署站点可正常运行,但本地启动时调试工具报500错误,终端显示Vite代理/graphql时触发AggregateError。以下是相关信息及排查建议:

终端错误日志

VITE v5.4.0  ready in 125 ms

  ➜  Local:   http://localhost:3000/
  ➜  Network: use --host to expose
  ➜  press h + enter to show help
10:45:13 PM [vite] http proxy error: /graphql
AggregateError
    at internalConnectMultiple (node:net:1114:18)
    at afterConnectMultiple (node:net:1667:5)

相关配置代码

Vite配置

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
    open: true,
    proxy: {
      "/graphql": {
        target: "http://localhost:3001",
        secure: false,
        changeOrigin: true,
      },
    },
  },
  test: {
    environment: "happy-dom",
    globals: true,
  },
});

server.js

const express = require('express');
const path = require('path');
// Import the ApolloServer class
const { ApolloServer } = require('@apollo/server');
const { expressMiddleware } = require('@apollo/server/express4');
const { authMiddleware } = require('./utils/auth');

// Import the two parts of a GraphQL schema
const { typeDefs, resolvers } = require('./schemas');
const db = require('./config/connection');

const PORT = process.env.PORT || 3001;
const server = new ApolloServer({
  typeDefs,
  resolvers,
  formatError(error) {
    console.log(error);
    return error;
  },
});

const app = express();

// Create a new instance of an Apollo server with the GraphQL schema
const startApolloServer = async () => {
  await server.start();

  app.use(express.urlencoded({ extended: false }));
  app.use(express.json());

  app.use(
    '/graphql',
    expressMiddleware(server, {
      context: authMiddleware,
    })
  );

  if (process.env.NODE_ENV === 'production') {
    app.use(express.static(path.join(__dirname, '../client/dist')));

    app.get('*', (req, res) => {
      res.sendFile(path.join(__dirname, '../client/dist/index.html'));
    });
  }

  db.once('open', () => {
    app.listen(PORT, () => {
      console.log(`API server running on port ${PORT}!`);
      console.log(`Use GraphQL at http://localhost:${PORT}/graphql`);
    });
  });
};

// Call the async function to start the server
startApolloServer();

客户端package.json

{
  "name": "client",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "@apollo/client": "^3.11.4",
    "@vitejs/plugin-react": "^4.3.1",
    "bootstrap": "^5.3.3",
    "graphql": "^16.9.0",
    "jwt-decode": "^4.0.0",
    "prop-types": "^15.8.1",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-router-dom": "^6.26.0",
    "vite": "^5.4.0"
  },
  "devDependencies": {
    "@testing-library/react": "^14.2.2",
    "@types/react": "^18.2.15",
    "@types/react-dom": "^18.2.7",
    "autoprefixer": "^10.4.19",
    "eslint": "^8.45.0",
    "eslint-plugin-react": "^7.32.2",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.3",
    "happy-dom": "^14.3.8",
    "vitest": "^2.0.5"
  }
}

服务端package.json

{
  "name": "apollo-mern",
  "version": "1.0.0",
  "description": "boilerplate code for MERN application",
  "main": "server/server.js",
  "scripts": {
    "start": "node server/server.js",
    "develop": "concurrently \"cd server && npm run watch\" \"cd client && npm run dev\"",
    "install": "cd server && npm i && cd ../client && npm i",
    "seed": "cd server && npm run seed",
    "build": "cd client && npm run build"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "concurrently": "^8.2.2",
    "react-icons": "^5.0.1"
  },
  "dependencies": {
    "autoprefixer": "^10.4.19",
    "hero-slider": "^3.2.1"
  }
}

已尝试的解决方案

  • 在客户端package.json中添加代理配置:"proxy": "http://localhost:5000"
  • 调整Vite配置和server.js中的端口设置
  • 更新所有依赖

排查与解决建议

  1. 确认后端服务是否正常启动

    • 检查服务端终端是否输出API server running on port 3001!和Use GraphQL at http://localhost:3001/graphql
    • 手动访问http://localhost:3001/graphql,确认Apollo Sandbox能正常加载,排除后端未启动或端口占用问题
    • 若端口3001被占用,修改server.js中的PORT为其他未占用端口(如5000),同步更新Vite配置中的target地址
  2. 修正Vite代理配置

    • 添加WebSocket支持,因为GraphQL可能使用WS连接:
      proxy: {
        "/graphql": {
          target: "http://localhost:3001",
          secure: false,
          changeOrigin: true,
          ws: true // 新增WebSocket支持
        },
      },
      
    • 移除客户端package.json中的proxy字段,Vite不依赖该配置,反而可能引发冲突
  3. 检查数据库连接状态

    • server.js依赖MongoDB连接(db.once('open', ...)),若本地MongoDB未启动,后端会卡在等待连接状态,无法响应请求
    • 启动本地MongoDB服务,或检查config/connection.js中的连接字符串是否指向本地实例
  4. 修复并发启动脚本

    • 根目录develop脚本中服务端的watch脚本不存在,修改为直接启动后端:
      "develop": "concurrently \"cd server && npm run start\" \"cd client && npm run dev\""
      
    • 或在服务端package.json中添加watch脚本并安装nodemon:
      "scripts": {
        "start": "node server.js",
        "watch": "nodemon server.js"
      }
      
      执行npm install nodemon --save-dev安装依赖
  5. 验证中间件顺序

    • 确保express.json()和express.urlencoded()中间件在expressMiddleware之前加载,保证请求体正确解析

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 18:16:00