部署到 Heroku 时,Express API 端点路由 return 404,在本地工作

Express API endpoint routes return 404 when deployed to Heroku, work locally

尝试制作一个简单的 React + Express 站点并将其部署到 Heroku 被证明是一项非常棘手的任务。在我的本地机器上工作的设置是:

  1. 方法一:我在root目录下运行npm startnpm startclient 目录,客户端 package.json 中的代理指向服务器 address/port.

  2. 方法二:我在客户端目录下运行npm run build,根目录下只运行npm start。 (为了测试这一点,我删除了检查生产的 if 语句,因此它会 运行 在开发中)

这两种方法在我的本地机器上都运行良好,但是当我部署到 heroku 时,在尝试导航到我的服务器端点 /api 时,我总是收到 404 错误。我在 SO 上看到了很多关于这个问题的帖子,并尝试了我阅读的所有建议,但都无济于事。

服务器 index.js

const express = require("express");
const PORT = process.env.PORT || 8080;
const app = express();
const path = require('path');
const cors = require('cors')
app.use(cors())

// API
const router = require('./router/index');
app.use("/api", router);

if (process.env.NODE_ENV === "production") {
  app.use(express.static(path.join(__dirname, "client", "build")))
      
  app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "client", "build", "index.html"));
  });
}

app.listen(PORT, () => {
  console.log(`app listening on ${PORT}`)
})

服务器 package.json

{
  "name": "ltb_calculator",
  "version": "1.0.0",
  "description": "An application for calculating interest for the Lifestyle Trading Bot on Telegram",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "install": "cd client && npm install",
    "build": "cd client && npm run build",
    "test": "mocha"
  },
  "engines": {
    "node": "^16.2.0"
  },
  "author": "Sonny Parlin",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "http-proxy-middleware": "^2.0.0",
    "mocha": "^9.0.0",
    "query-string": "^7.0.0",
    "react-fetch-hook": "^1.8.5",
    "react-json-view": "^1.21.3"
  }
}

客户端 package.json

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:8080",
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

整个项目都在 github、here 上。从 SO 上有关此问题的数量来看,许多人出于各种不同的原因 运行 正在关注此问题。提前感谢您的任何见解。

我使用了错误的构建包。我不记得设置了一个构建包,它可能是 heroku 添加的东西。无论如何,我删除了 react buildpack 并添加了一个 nodejs buildpack,这似乎已经解决了我的问题。它一定是 运行 React 服务器而不是 Express 服务器。