HEROKU Cannot GET /*any page*

Viewed 437

I am looking for help. Please. I am learning to code and build web pages/applications. Currently, stack with an error that I don't know how to fix as the local version runs with no issues but deployed version gets an error. Previously deployed a similar webpage with no issues.

I have deployed on Heroku (deployed and built with no issues in logs) an application with client-side (React) and server-side (Apollo & graphQL & mongoDB). I can load the main page with login or register, log in and see a profile with all data fetched. However, when I refresh the /profile page or even simple pages like /contact or /about, I get an error.

> Cannot GET /page

Console

> Failed to load resource: the server responded with a status of 404 (Not Found)

Please see below the codes.

server/server.js

const express = require("express");
const { ApolloServer } = require("apollo-server-express");
const path = require("path");

const { typeDefs, resolvers } = require("./schemas");
const { authMiddleware } = require("./utils/auth");
const db = require("./config/connection");

const PORT = process.env.PORT || 3001;
const app = express();

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: authMiddleware,
});

server.applyMiddleware({ app });

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

if (process.env.NODE_ENV === "production") {
  app.use(express.static(path.join(__dirname, "../client/build")));
}

db.once("open", () => {
  app.listen(PORT, () => {
    console.log(`  Now listening on port ${PORT}!  `);
    console.log(
      ` Server ready at http://localhost:${PORT}${server.graphqlPath} `
    );
  });

client/src/App.js

import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { ApolloProvider } from "@apollo/react-hooks";
import ApolloClient from "apollo-boost";

import Navbar from "./components/Nav";
import Footer from "./components/Footer";
import { PrivateRoute } from "./components/PrivateRoute";
import { PublicRoute } from "./components/PublicRoute";

import Home from "./pages/Home";
import Login from "./pages/Login";
import Register from "./pages/Register";
import Profile from "./pages/Profile";
import About from "./pages/About";
import Contact from "./pages/Contact";
import Runsheet from "./pages/Runhseet"
import Summary from "./pages/Summary";

const client = new ApolloClient({

  request: (operation) => {
    const token = localStorage.getItem("id_token");

    operation.setContext({
      headers: {
        authorization: token ? `Bearer ${token}` : "",
      },
    });
  },
  uri: "/graphql",
});

function App() {
  return (
    <ApolloProvider client={client}>
      <Router>
          <section className="hero is-success is-fullheight">
            <Navbar />
            <Switch>
              <PublicRoute path="/" exact component={Home} />
              <PublicRoute path="/login" exact component={Login} />
              <PublicRoute path="/register" exact component={Register} />
              <PrivateRoute path="/profile" exact component={Profile} />
              <PrivateRoute path="/runsheet" exact component={Runsheet} />
              <PrivateRoute path="/summary" exact component={Summary} />
              <Route path="/about" exact component={About} />
              <Route path="/contact" exact component={Contact} />
            </Switch>
            <Footer />
          </section>
      </Router>
    </ApolloProvider>
  );
}

export default App;

client/src/static.json (found as a solution on one of the similar questions, however, didn't help me, still getting the same issue).

{
    "root": "build/",
    "clean_urls": false,
    "routes": {
      "/**": "index.html"
    }
  }
1 Answers

Found the answer after many hours of research and retyping

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