【问题标题】:MERN App Deployed to Heroku Not Working Properly部署到 Heroku 的 MERN 应用程序无法正常工作
【发布时间】:2018-12-18 09:30:19
【问题描述】:

我已将 MERN 应用部署到 Heroku。当我打开应用程序时,我可以通过我的 API 将数据发布到 MongoDB 数据库,但是,每当我发出 GET 请求时,Heroku 都会回复:

at=info method=GET path="/api/lists/5b44001a558fe30014e8c43c" host=bootcamp-bucket-list.herokuapp.com request_id=e9b06431-aa30-4811-bf7d-a46720991646 fwd="24.124.88.220" dyno=web.1 connect=0ms service=2ms status=304 bytes=237 protocol=https

我能够在我的服务器上本地运行该应用程序而没有任何问题,只是当我们处于生产状态时,GET 请求失败。有没有人经历过这种情况并知道可能导致此问题的原因?如果需要任何其他信息,请告诉我。

这是我的server.js 文件的设置:

const express = require('express');
const path = require('path');

const users = require('./routes/api/users');
const routes = require('./routes');
const app = express();
const port = process.env.PORT || 5001;

const bodyParser = require("body-parser");
const passport = require('passport');
const mongoose = require("mongoose");
const Models = require('./models');
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());

mongoose.Promise = Promise;
var MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost/testdb";
console.log(MONGODB_URI);
mongoose.connect(MONGODB_URI);
const db = mongoose.connection;

app.use(passport.initialize());

// PASSPORT CONFIG
require('./config/passport')(passport);


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

if (process.env.NODE_ENV === 'production') {
  // Serve any static files
  app.use(express.static('client/build'));
}

// USE ROUTES
app.use('/api/users', users);
app.use(routes);

app.listen(port, () => console.log(`Listening on port ${port}`));

我的package.json 文件中还有以下脚本:

"start": "node server.js",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"

【问题讨论】:

    标签: node.js reactjs heroku redux


    【解决方案1】:

    您需要确保在生产模式下运行时保留您的 api 端点。

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

    应该是这样的

    if (process.env.NODE_ENV === 'production') {
      app.use(express.static('client/build')); // serve the static react app
      app.get(/^\/(?!api).*/, (req, res) => { // don't serve api routes to react app
        res.sendFile(path.join(__dirname, './client/build/index.html'));
      });
      console.log('Serving React App...');
    };
    

    【讨论】:

    • 实际上,我刚刚清除了缓存,现在当我访问该站点时,我得到了一个Not Found。这是 Heroku 日志中出现的错误:Error: ENOENT: no such file or directory, stat '/app/dist/index.html'
    • 更新了答案以反映您问题中的路径,错误是说您的 index.html 路径不正确。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 2023-03-23
    • 2017-11-06
    • 1970-01-01
    相关资源
    最近更新 更多