Reputation: 13
I've deployed a MERN app to Heroku. When I go to the app, I'm able to post data through my APIs to the MongoDB database, however, whenever I make a GET
request, Heroku responds with:
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
I am able to run the app locally on my servers without any issues, it's just when we're in prodution, the GET requests fail. Has anyone experienced this before and know what could be causing this issue? Let me know if any additional info is needed.
Here is the setup of my server.js
file:
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}`));
I also have the following scripts in my package.json
file:
"start": "node server.js",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
Upvotes: 1
Views: 1779
Reputation: 389
You need to make sure that when running in production mode that you are reserving your api endpoint.
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, './client/build/index.html'));
});
should be something like
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...');
};
Upvotes: 1