DNY node api (1 – setup)

  • download source
  • unzip the source code
  • go into directory and type npm install to install the modules
  • Once the packages are installed, run it npm run dev
  • Go to localhost:8080, then check terminal for logs

Set up

Open terminal, navigate to ‘Desktop’

mkdir dnyNodeAPI

cd dnyNodeAPI

npm init

press enter for all selections

npm install express

Then check your node_modules folder and you’ll see whole of packages being installed.

In our package.json file, change ‘main’: ‘index.js’ to ‘main’: ‘app.js’

Create file ‘app.js’:

in your terminal, if you went node app.js, it will run the server on port 8080.

But whenever we make a code change, we have to restart the server and this becomes cumbersome. So let’s install nodemon.

npm i nodemon

Then in your package.json:

Now, in your terminal, Ctrl+C to get out of whatever is running.
Then npm run dev.
It will run the command as specified in our package.json and we get the server running with constant updates.

Putting in Routes

routes/posts.js

app.js

Install Middleware

npm i morgan

Installing Database

Create account in mLab, and create a database. Select default for everything, i.e AWS, server at Europe, and create submit. Then ‘create db user’, and create a username and pwd for the db’s user.

Then, in your project, create a file .env:

.env

npm i dotenv

npm i mongoose

app.js

post.js

post.js