11/1/2017 - 1:28 AM

Initial server setup

  • npm i --save body-parser
  • look at package.json for "main":"index.js". Create a file with this name and extension.

1. Index.js // entry point of server

import express from 'express';

const app = express();  //run instance of express </br>
const PORT = 3000;  //variable for port

app.get('/', (req, res) => //make sure we get something in return when we call URL
  res.send(`Node and express server is running on ${PORT}`)  //message will return on localhost 3000; template strings using ES6 syntax

app.listen(PORT, () =>
  console.log(`your server is running on port${PORT}`)

2. package.json //Script for Start Command

"start": "nodemon ./index.js --exec babel-node -e js"

3. Setting up folder structure: start with everything in src folder then start branching out the folders and files to controllers, models, and routes

  • create new folder called SRC (source).
    • Inside this folder create your Controllers folder. This is where we're going to have most to the logic of our server, so when we need to return specific data and send it to our API, then this is where our controllers are going to be.
    • Inside SRC, create Models folder. This is where we are going to create our schema, this is where we're goin g to connect to mongodb
    • Inside SRC, create Routes folder. This is where we create our API endpoints so that we can call a URL and get something back in a web app.

4. Routes and endpoints

You can call a route and go to a specific page or you can also use routes to define your endpoints in an application.


 const routes = (app) => { // we are passing (app) inside of our routes function inside of our index in order to pass the endpoints that we'll just created. 
   //so here we're going to make several types of calls, a GET call to return all of our contacts and a POST call to add a new contact, all use same URL.
   .get((req,res) =>
   res.send('GET request successful'))
   .post((req,res) =>
   res.send('POST request successful'));
 //next route
   .put((req,res) =>
   res.send('PUT request successful'))
   .delete((req,res) =>
   res.send('DELETE request successful'));
   //The last thing that we need to do is make sure that we export that particular function otherwise we won't be able to use it anywhere else in our application.
   export default routes;

5. Index.js

// import routes from routes.js

import express from 'express';
import routes from './src/routes/crmRoutes';// imported routes 

//And then all we need to do at this point is to run it. So we are running the function routes and guess what, we're passing app to it. So therefore, once we run this application, we're going to pass express to it and be able to basically have those api calls available.

routes(app);//now test with Postman