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
express
as a dependency: -
Make a
src
directory inside your project folder. Put anapp.js
file in there.-
Require express at the top of the file:
const express = require('express');
-
Call express as a function, and assign it to a
const
calledapp
:const app = express();
-
We know that we will need to be able to access the
request.body
in 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_PORT
and set it to a value of 4000. This is the port that we will configure our app to listen on. -
Call
app.listen
as a function. The first argument it takes will beAPP_PORT
. -
The second argument
app.listen
will 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
nodemon
as adev dependency
using the-D
flag by runningnpm i -D nodemon
-
Add a
start
script to yourpackage.json
. It should run the commandnodemon index.js
-
Test your
start
script by runningnpm start
in 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.