Monday, September 2, 2024

Boilerplate NPM NodeJS Express

MyApp.js

require('dotenv').config()
let bodyParser = require('body-parser')
let express = require('express');
let app = express();
let viewpath = __dirname + '/views/'
let indexpath = viewpath + 'index.html'
let publicpath = __dirname + '/public'
app.use('/public', express.static(publicpath));
app.use(logger);
app.use(bodyParser.urlencoded({extended: false}));

function logger (req, res, next) {
  var string = req.method + " " + req.path + " - " + req.ip;
    console.log(string);
  next();
}

function stringresponse (req, res) {
  res.send('Hello Express');
}

function jsonresponse (req, res) {
  let data = {"message": "Hello json"};
    // console.log(process.env.MESSAGE_STYLE == "uppercase")
    if (process.env.MESSAGE_STYLE == "uppercase") {
        data['message'] = data['message'].toUpperCase()
    }
    res.json(data);
}

function fileresponse (req, res) {
  // console.log(req.method, req.path, req.ip);
    res.sendFile(indexpath);
}

app.get('/', fileresponse)
app.get('/json', jsonresponse)
app.get('/now', function(req, res, next) {
  let timenow = new Date().toString()
    req.time = timenow;  // Hypothetical synchronous operation
  next();
}, function(req, res) {
  res.json({'time': req.time});
});
app.get('/:word/echo', function(req, res, next) {
    req.echo = req.params.word;  // Hypothetical synchronous operation
  next();
}, function(req, res) {
  res.json({'echo': req.echo});
});

app.route('/name').get(getnamehandler).post(postnamehandler)
function getnamehandler(req, res) {
    let reqquery = req.query;
    let first = reqquery['first']
    let last = reqquery['last']
    let fullname = first + ' ' + last
    console.log('get req.query', reqquery);
  res.json({'name': fullname});
};

function postnamehandler(req, res) {
    let reqbody = req.body;
    let first = reqbody['first']
    let last = reqbody['last']
    let fullname = first + ' ' + last
    console.log('post req.body', fullname);
  res.json({'name': fullname});
};

 module.exports = app;

server.js

/******************************************************
 * PLEASE DO NOT EDIT THIS FILE
 * the verification process may break
 * ***************************************************/
 
const bGround = require('fcc-express-bground');
const myApp = require('./myApp');
const express = require('express');
const app = express();

if (!process.env.DISABLE_XORIGIN) {
  app.use((req, res, next) => {
    const allowedOrigins = ['https://narrow-plane.gomix.me', 'https://www.freecodecamp.com'];
    const origin = req.headers.origin || '*';
    if(!process.env.XORIG_RESTRICT || allowedOrigins.indexOf(origin) > -1){
         console.log(origin);
         res.setHeader('Access-Control-Allow-Origin', origin);
         res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    }
    next();
  });
}

const port = process.env.PORT || 3000;
bGround.setupBackgroundApp(app, myApp, __dirname).listen(port, () => {
  bGround.log(`Node is listening on port ${port}...`);
});

/******************************************************
 * PLEASE DO NOT EDIT THIS FILE
 * the verification process may break
 * ***************************************************/
 views/index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>Hello HTML</title>
        <link rel="stylesheet" href="/public/style.css">
    </head>
    <body>
        <h1>Hello, HTML.</h1>
        <p>Do not use until Challenge #12</p>
     <form action="/name" method="post">
      <label>First Name :</label>
      <input type="text" name="first" value="John"><br>
      <label>Last Name :</label>
      <input type="text" name="last" value="Doe"><br><br>
      <input type="submit" value="Submit">
    </form>
    </body>

</html>

public/style.css

/* the 'body' selector is required for the tests to pass */
/* You can change the style attributes if you want */
body {
  background-color: #222;
  color: #ddd;
  text-align: center;
  font-family: sans-serif;
}

h1 {
  font-size: 4em;
}

input[type=text], label {
  margin-bottom: 8px;
}

package.json

{
  "name": "fcc-learn-node-with-express",
  "version": "0.1.0",
  "dependencies": {
    "body-parser": "^1.15.2",
    "cookie-parser": "^1.4.3",
    "dotenv": "^16.0.1",
    "express": "^4.14.0",
    "fcc-express-bground": "https://github.com/freeCodeCamp/fcc-express-bground-pkg.git"
  },
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  }
}

readme.json

Basic Node and Express

This is the boilerplate code for the Basic Node and Express Challenges. Instructions for working on these challenges start at https://www.freecodecamp.org/learn/apis-and-microservices/basic-node-and-express/