Setting Up the Application (Manual)
Please note ⚠️
If you used the @command-shift/create-backend-app script, you do not need to follow these manual steps. The script has already done all the required setup mentioned on this page. Feel free to read through if you want a better understanding of what the script did.
Manually setting up the app
Now that we have a blank repo, it's time to start setting up a basic Express application.
Express
-
Install
expressas a dependency: -
Make a
srcdirectory inside your project folder. Put anapp.jsfile in there.-
Require express at the top of the file:
const express = require('express'); -
Call express as a function, and assign it to a
constcalledapp:const app = express(); -
We know that we will need to be able to access the
request.bodyin this project, so we should also configure the app to useexpress.json:app.use(express.json()); -
Finally, export your app at the bottom of the file with
module.exports = app;
-
-
Make a file in the root of project called
index.js.-
Require your app at the top of this file.
-
Declare a const called
APP_PORTand set it to a value of 4000. This is the port that we will configure our app to listen on. -
Call
app.listenas a function. The first argument it takes will beAPP_PORT. -
The second argument
app.listenwill take is an arrow function. In this arrow function you shouldconsole.log(`App is listening on port ${APP_PORT}`)
-
Your src/app.js should now look like this:
And your index.js should look like this:
If you run the command node index.js in the terminal, you should see that your app is running. It won't do anything yet though, we haven't given it any routes or controllers.
Right now, we will need to restart our app every time we make any changes to the code. This can get tedious fast. To help make the development cycle a bit smoother, we will use nodemon.
Nodemon
Nodemon (short for node demon), is a package which will watch our project files and wait for them to be updated. When it detects this, it will restart our application. This means that any changes to the code will be reflected in our app right away.
-
Install
nodemonas adev dependencyusing the-Dflag by runningnpm i -D nodemon -
Add a
startscript to yourpackage.json. It should run the commandnodemon index.js -
Test your
startscript by runningnpm startin your terminal.
Finally
Add a get route to / in your app.js. It should return a 200 status code and a Hello World string. Run your app and send a GET request to localhost:4000 in postman. If you get a Hello World then you know that your app is working.