jas0nhuang

Build a Basic M.E.N. Site - 1 - NodeJS/Express Server

This is my note trying to build a basic M.E.N.(MongoDB, Express, NodeJS) stack web site.
Most of the steps are following the posts of ZELL LIEW : Building a Simple CRUD Application with Express and MongoDB.

Start

  1. Create project folder
  2. Run npm init inside the folder. Press enter for everything.
  3. Create server.js file touch server.js. Write some LOGLOG inside and run it with node server.js.

Basic Backend Structure with NodeJS and Express

Start using Express

  1. npm install express --save. The –save option will install third-party package to the package dependencies.
  2. Check package.json file if the dependency is added.
  3. use express in server.js app.
    // first require it.
    const express = require('express');
    const app = express();

    // Second. Create a server with .listen method provided by Express.
    app.listen(3000, function(){
    console.log("We are listening on port 3000")
    })

GET to Read something

  1. Can run server.js with node. But still no page servered. So there will be a “Cannot GET /“ message if we connect to localhost:3000.

  2. Read operation: Use the .get method to handle a GET request:

    app.get(path, callback)

    path will be “/“ here.
    callback stars a “callback function” if the path is matched. and this “function” takes a request object and a response object.

  3. Say “HELLO” with the .send method in response object.

    app.get("/", function(req, res){
    res.send("Now you see me.")
    })

    This should SEND the message “Now you see me.” to the browser.

  4. Serve an index.html to the browser:
    use the .sendFile method insted:

    res.sendFile(__dirname + "/index.html")
    // __dirname is dir that contains the JS source code. LOG it to see the path?!

    TOUCH an index.html file to be servered

Nodemon

With the nodemon package we can let the server restarts automatically.

  1. Install nodemon
    npm install nodemon --save-dev
    // --save-dev because this package is only used developing. So it will be write to devDependency in package.json.
  2. Use nodemon
    nodemon server.js
    won’t work since nodemon is not installed with -g.
    ./node_modules/.bin/nodemon server.js
    or create a script key in package.json:
    {
    "scripts":{
    "dev":"nodemon server.js"
    }
    }
    and we can run npm run dev to trigger nodemon server.js

Basic DOM Manipulation

POST some Creativety

  1. Create operation: Use .post method to Create things back to server.
    It can be done by JavaScript or html

    element.

  2. Try with the <form> now:
    Need to have action and method attributes in the <form> tag and name attributes on all <input> tags:

    <form action="/plusorminus" method="POST">
    <input name="FacebookName" type="text" placeholder="Your Name">
    <span> prophesy:</span>
    <br>
    <label value="21032020">New cases on 06/04/2020 will be</label>
    <br>
    <input name="date" type="hidden" value="21032020">
    <button class="plusbutton" type="submit" name="plusorminus" value="+">More</button>
    <span>/</span>
    <button class="minusbutton" type="submit" name="plusorminus" value="-">Less</button>
    <br>
    <span>then the new cases on 05/04/2020</span>
    </form>

    “action” attribute finds the path. “method” defines the request to send.

  3. Serverside handle the POST request with “.post” method with Express. Same arguments as the “.get” method.

    app.post("/quotes",function(req, res){
    console.log("Now you see me again!")
    })

Parse the body

  1. Express can’t handle reading data from the . So we need “body-parser” package as a middleware to do this.
    npm install body-parser --save
  2. Add the functionality in the server.js. (Make sure to place body-parser before the CRUD handlers!)
    const bodyParser = require("body-parser")
    app.use(bodyParser.urlencoded({extended: ture}))
    (I don’t understand what .urlencoded() function does, but it works anyways.)

Now that we have a basic NodeJS/Express server with a minimal HTML page. Need to proceed to the CRUD(Create, Read, Update, Delete) part of this site.