Boilerplate: Node JS and others

Boilerplate highlighted in Purple 

Use user input to return a result

const express = require("express"); // Express.JS Boilerplate highlighted in Purple

const bodyParser = require("body-parser"); // Required package to process data of user inputs

const app = express();

app.use(bodyParser.urlencoded({extended: true})); // Required, otherwise the req.body.x below won’t work

const port = 3000;

app.get("/", function(req, res) {

  res.sendFile(__dirname + "/function.html"); // send the webpage to return, vs. res.send("working fine");

})

app.post("/function", function(req, res) {

  var myVAR = Number(req.body.formInputName); // Get the data from the user input on sendFile (“/function.html”), and store it as number

  var result = myFunction(myVAR); // Call myFunction with the input from the user

  res.send(result); // return the result to the webpage

})

 

function myFunction(myVariable) {…} // define the function used in app.post

 

app.listen(port, function() {

  console.log("server has started");

});

///* on function.html *///

<form action="/function" method="post">

<input type="text" name="formInputName" placeholder="placeholder">

<button type="submit" name="submit">Submit</button>

</form>

Making API Requests with the Node HTTPS Module

const express = require("express");

const https = require("https"); // already embedded with Node.js

const app = express();

const port = 3000;

app.use(express.static(“public”)); // allow the server to fetch files from “public” folder, and in html when link to the files in public folder, no need to include public in the path, e.g. link= “images/pic.png” 

app.get("/", function(req, res) {

  const url = “https://....” //API link

  https.get(url, function (response){

  console.log(response.attributesIWant) // return the attribute the url

  response.on(“data”, function(data){

   const returnedDataset = JSON.parse(data) ;// return the dataset from the API, reverse of JSON.stringify()

   const returnedSpecificData1 = returnedDataset.path ;// return the specific data from the API

   const returnedSpecificData2 = returnedDataset.path ;   

   res.write(returnedSpecificData1);

   res.write(returnedSpecificData2);

   res.send(returnedSpecificData1); // res.send can only appear once

})

});

 

app.listen(port, function() {

  console.log("server has started");

});

 

 Signup Webpage and upload to online server

//jshint esversion:6

const bodyParser = require("body-parser");

const express = require("express");

const request = require("request");

const https = require("https");

const app = express();

app.use(express.static("public"));

app.use(bodyParser.urlencoded({extended: true}));

app.get("/", function(req, res) {

  res.sendFile(__dirname + "/signup.html");

});

app.post("/", function(req, res) {

  const firstName = req.body.fName;

  const lastName = req.body.lName;

  const email = req.body.email;

  const data = {

    members: [{

      email_address: email,

      status: "subscribed",

      merge_fields: {

        FNAME: firstName,

        LNAME: lastName

      }

    }]

  };

  const jsonData = JSON.stringify(data);

  const url = "https://us20.api.mailchimp.com/3.0/lists/e6c65027ef";

  const options = {

    method: "POST",

    auth: "anyUserName:19ced65969b0f49ccb88e8da2d824768-us20"

  };

  const request = https.request(url, options, function(response){

    if(response.statusCode===200)

    {

      res.sendFile(__dirname + "/success.html");

    }else{

      res.sendFile(__dirname + "/failure.html");

    }

    response.on("data", function(data){

      console.log(JSON.parse(data));

    });

  });

  request.write(jsonData);

  request.end();

});

app.post("/failure", function(req,res){

  res.redirect("/"); //add a button in failure.html, and direct its route to /failure

});

app.listen(process.env.PORT || 3000, function() { //listen on process.env.PORT (online server) or local server 3000

  console.log("server is running on port 3000");

});

 

EJS

const app = express();

const myModule = require (__dirname+ “/myModule.js”); // recall own module;

var value1 = myModule.myFunction1() // run the function in myModule.js

app.set(‘view engine’, ‘ejs’);  // add this code in order to use EJS

var myArrays=[];

app.get("/", function(req, res) {

  var myVar;

  res.render(“index, {myVarInEJS: myVar, myArraysInEJS: myArrays});  // create a folder “views” and a file index.ejs inside this folder. Remove index.html

});

app.post(“/”, function(req, res){

 var myArray = req.body.myArrayInEJS;

 myArrays.push(myArray); //add the input to the collections

 res.redirect(“/”); //refresh the webpage every time the user submit the form

});

app.listen(…);

 

///* index.ejs *///

<%- include(“header”) -%> // include the header.ejs in the views folder

<h1>This is my <%= myVarInEJS %> </h1> // fetch the variable

<% if (myVar === A) { %> // every line that is not html, need to add <%...%>

<h1>…</h1>

<%}else{ %>

<h1>…</h1>

<%}%>

<form action= “/” method= “post”> // form for user to input

<input type=”text” name= “myArrayInEJS”>

<button type= “submit” name= “button”> Add </button>

</form>

<% for (var i=0; i< myArraysInEJS.length; i++) { %> // use for loop to render the lists

<li> <%= myArraysInEJS[i] %> </li>

<%}%>

<% myArraysInEJS.forEach(function(a){ %> // another way to loop an array

<h2><%= a.title %></h2>

<% }) %>

<%- include(“footer”) -%> // include the footer.ejs in the views folder

///* myModule.js */// parallel to app.js

exports.myFunction1 = function(){…};

exports.myFunction2 = function(){…};

0 Comments