Step 2

We need to refactor the API server to access the express app without binding it to a port. We require this change to run and test the app without running the server!

Open the server/index.js and remove the following lines and instead export the app:

+ 
- const db = require("./data/db");
  const notes = require("./routes/notes.js");
  const users = require("./routes/users.js");
  const auth = require("./routes/auth.js");

  const express = require("express");
  const app = express();
- const port = process.env.PORT || 5000;

- db.connect(); // no need to await for it due to Mongoose buffering!

  app.use(express.json());

  app.get("/", (req, res) => {
    res.send("QuickNote API!");
  });

  // routing
  app.use(notes);
  app.use(users);
  app.use(auth);

- app.listen(port, () => {
-   console.log(`Express app listening at port: http://localhost:${port}/`);
- });
+ module.exports = app;

Next, open server/data/db.js and remove the following:

- require("dotenv").config();

Next, create a new file, index.js, at the root of the project:

const app = require("./server");
const db = require("./server/data/db");

db.connect(); // no need to await for it due to Mongoose buffering!

const port = process.env.PORT || 5000;

app.listen(port, () => {
  console.log(`Express app listening at port: http://localhost:${port}/`);
});

Next, update the "scripts" in package.json:

-   "dev": "nodemon server",
+   "dev": "nodemon .",
-   "start": "node server",
+   "start": "node .",

Finally, update the Procfile:

-  web: node ./server/index.js
+  web: node ./index.js

Save all the changes and run the server using npm run dev. Try the API in Postman to ensure it works as expected.