【发布时间】:2020-05-05 09:40:47
【问题描述】:
我正在努力将我的 react 应用程序部署在 Heroku 上,但在一个又一个问题中遇到了问题。我对开发/反应相当陌生(所以这可能在这里做一些愚蠢的事情),但我一直能够在本地成功运行应用程序。
首先,这是我的错误: `
反应脚本构建 找不到所需的文件。 名称:index.html 搜索:/tmp/build_7ddb1c907b9746a90f2bd6108231f553/public`
Where index.html resides in my codebase
这是我的 package.json 的相关部分:
"name": "mern-auth",
"version": "1.0.0",
"homepage": "./",
"description": "Mern Auth Example",
"main": "server.js",
"node": "v12.13.1",
"npm": "6.13.4",
"scripts": {
"client-install": "npm install --prefix client",
"build": "react-scripts build",
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku": "npm run build && copy client/public/index.html dist/index.html"
},
(为了尝试让 Heroku 识别 index.html,我已经对 heroku 脚本进行了大量修改。我知道目前存在的内容可能不正确,但坦率地说,我不确定是否有更好的选择。 )
这是我的 server.js 文件的科学怪人:
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const path = require('path');
const users = require("./routes/api/users");
const plaid = require("./routes/api/plaid");
const app = express();
const publicPath = path.join(__dirname, '..', 'public');
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
app.use(express.static('dist'));
/* app.use(express.static(publicPath)); */
/* app.get('*', (req, res) => {
res.sendFile(path.join(publicPath, 'client/public/index.html'));
}); */
/* app.listen(port, () => {
console.log(`Server started on port ${port}.`);
}); */
/* app.get('*', (req, res) => {
res.sendFile('../public/index.html', {root: __dirname})
}); */
const morgan = require("morgan");
app.use(morgan("tiny"));
// Serve our api message
app.get("/api/message", async (req, res, next) => {
try {
res.status(201).json({ message: "HELLOOOOO FROM EXPRESS" });
} catch (err) {
next(err);
}
});
if (process.env.NODE_ENV === "production")
// Express will serve up production assets
app.use(express.static("build"));
// Express will serve up the front-end index.html file if it doesn't recognize the route
app.get('*', function(request, response) {
response.sendFile(path.resolve(__dirname, '../client/public', 'index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log('Server is up!');
});
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log("MongoDB successfully connected"))
.catch(err => console.log(err));
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/users", users);
app.use("/api/plaid", plaid);
从 server.js 中注释掉的代码可以看出,我已经尝试了许多变通方法来尝试使其正常工作。我在这里的首要任务是能够让它运行。理想情况下,我希望能够使用我在脚本中定义的 npm run build 命令在生产状态下执行此操作,但我非常乐意部署开发版本。无论您能提供什么帮助,我们都将不胜感激!
【问题讨论】:
标签: node.js reactjs react-native express heroku