事实证明,尝试制作一个简单的 React + Express 站点并将其部署到 Heroku 是一项相当棘手的任务。在我的本地计算机上运行的设置是:
方法 1:我在 root 目录中运行
npm start
,然后在 client< 中运行npm start
/strong> 目录,客户端的 package.json 中的代理指向服务器地址/端口。方法 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 上有关此问题的数量来看,许多人出于多种不同的原因遇到了这个问题。预先感谢您的任何见解。
最佳答案
我使用了错误的构建包。我不记得设置了 buildpack,这可能是 heroku 添加的东西。不管怎样,我删除了react buildpack并添加了一个nodejs buildpack,这似乎解决了我的问题。它必须运行的是 React 服务器而不是 Express 服务器。
关于node.js - Express API端点路由部署到Heroku时返回404,在本地工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67976191/