我想弄清楚如何将 react-express 应用程序部署到 Heroku,因此我创建了一个非常简单的应用程序来执行此操作。它是一个带有快速后端的 create-react-app
前端,在 localhost:3000 有一个开发服务器,它代理对位于 localhost:5000 的服务器的 api 调用。
但是,每当我尝试加载应用程序的 URL 时,我都会收到“应用程序错误”,在检查错误日志后,我注意到以下错误:
Error: Cannot find module '/app/index.js'
app[web.1]: at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)
app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:667:27)
app[web.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
app[web.1]: at internal/main/run_main_module.js:17:47 {
app[web.1]: code: 'MODULE_NOT_FOUND',
有关如何解决此问题的任何提示?
这是我的项目结构:
client
+-build
+-node_modules
public
+-index.html
src
+-App.js
+-index.js
package.json
yarn.lock
server
+-models
+-reviews.js
+-node_modules
+-package.json
+-server.js
+-yarn.lock
这是我配置服务器的方式:
const express = require('express');
const cors = require('cors')
const bodyParser = require('body-parser');
const mongoose = require('mongoose')
const Review = require('./models/reviews')
const path = require('path')
//Server
const app = express();
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));
//Middleware
app.use(express.static(path.join(__dirname, 'build')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded())
app.use(cors())
//Mongo config
const dbURI = 'mongodb+srv://joshydsimon:Josh1985!@mochawelly.8cxdz.mongodb.net/MochaWelly?retryWrites=true&w=majority'
mongoose.connect(dbURI, {useNewUrlParser:true, useUnifiedTopology:true})
.then(() => {
console.log('connected to db')
})
.catch((err) => {
console.log(err)
})
app.get('/api/all-reviews', (req,res) => {
Review.find()
.then((result) => {
res.send(result)
})
.catch(err => {
console.log(err)
})
})
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
最后,这是我添加到 package.json(服务器端)中的一些脚本:
"start": "node index.js",
"heroku-postbuild": "cd client && npm install && npm run build",
答案 0 :(得分:0)
它可能没有指向您的客户端文件夹?
//Try this?
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
也试试这个:
"scripts": {
"client-install": "npm install --prefix client",
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"}
也试试这个:
app.use(express.static(path.join(__dirname, 'client/build')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded())
app.use(cors())