- Initialise the project with npm init -y
npm init -y
- Install express and express-handlebars inside of your application then add them to your index.js along with path
npm i express express-handlebars
const express = require('express');
const hbs = require('express-handlebars');
const path = require('path');
const app = express(); //initialise express as a function
- Basic folder structure for our application
project
│ index.js
│ readme.md
│
└───lib
│ HarryPotter.js
│
└───public
│ style.css
│
└───views
│ └───layouts
│ layout.hbs
│ index.hbs
- Create your app.get and app.listen for your basic express web-server
app.get('/', async (req, res) => {
res.render('index');
});
app.listen(3000, () => {
console.log('listening on port 3000');
});
- Above the app.get but below the const imports, put the following to setup the path for our style.css and other client-side code and the creation of the HBS template:
app.use(express.static(path.join(__dirname, 'public')));
app.engine('.hbs', hbs({
defaultLayout: 'layout',
extname: 'hbs'
}));
app.set('view engine', '.hbs');
- Setup your layout.hbs like a normal HTML file with a CSS link with a twist
- Head to the HarryPotter.js inside of the lib folder now and insert the following for a Harry Potter API function:
const fetch = require('node-fetch');
const URL = `https://www.potterapi.com/v1/sortinghat`
const getSortingHat = async () => {
let data = await fetch(URL);
let JSObject = await data.json();
return JSObject;
}
module.exports = {
getSortingHat
}
- Head back to your index.js in the root folder and import your file you just exported near the top of your file:
// below your external module imports
const API = require('./lib/HarryPotter.js');
// above your app.use
- Next, let's go back to our app.get('/') and modify it like this:
let data = await HarryPotter.getSortingHat();
console.log(data)
res.render('index', { data });
- We have put data inside of an object in the res.render, so, in our index.hbs, let's put this:
- We currently don't have a .env, so let's set that up:
// npm i dotenv
require('dotenv').config(); // create a .env file and .gitignore
- Run nodemon and load our localhost:3000
- Routes
- controllers
- model folder
Why? Each project should be set up in the best way for the progression of the project. This project currently works well for what it is, it is a node & handlebars template, but we will be adding a controllers and models section to this template. Even if it is empty, we want the correct set up to be there for the project.
Coming soon.