$ node
> 1 + 2
3
> const express = require('express');
...
> .exit
They're what you get back from a request 😎
"Routes" define how a server should respond to a certain request at a certain end point or path.
// app.<HTTP action>
app.get('/', function (req, res) {
res.send('Hello World!');
});
Our controllers mediate communication between our models and views
exports.index = function (req, res) {
res.send('Welcome to the GDI Node Workshop!');
}
A node module is a file, and it exposes things to the outside world with exports
exports.index = function (req, res) {
res.send('Welcome to the GDI Node Workshop!');
}
var express = require('express');
// var nameWeUseInOurApp = require('someModule');
// Tell app.js about the home controller using require
// Node how the ./ tells node to look in our own folder structure vs node_modules
var homeController = require('./controllers/home');
// Routes
app.get('/', homeController.index);
home.js
file in a controllers
folder.home.js
app.js
to use your controller./*
route as a catch-all displays a 404 message./about
Pass data through to your view
var path = require('path');
exports.index = function (req, res) {
res.sendFile(path.join(__dirname, '../public', 'templates', 'index.html'));
}
We need to tell Express which files we allow the user to access
// Serve static files (i.e. images, scripts, styles, templates) from public/ directory
app.use(express.static('public'));
index.html
/about
if you haven't yet/about
with a new templateBecause writing HTML can be a lot! And view engines are great!
Check out Pug (formerly known as Jade)'s site for examples and an interactive playground
// template.pug
h1 Welcome
a(href="somewhere.com") Some cool link!
Install & Use Pug
npm install --save pug
// in app.js
app.set('view engine', 'pug');
Use res.render
to use your view engine
exports.about = function (req, res) {
res.render('about');
}
Since we put our about.pug
file in views/
Express knows where that is and assumes that's what we mean when we say render
npm install --save-dev nodemon
and update your package.json
to use nodemon to run app.js
. It will live reload so you don't have to start/stop your server!
.pug
views to a views
folderApplication Programming Interface
AKA computers talk to each other
APIs allow us to request data from a service
Some APIs you might want to use
/api/all
/api/get/:id
where id is the index of the dinosaurExercise solutions at https://github.com/pselle/Intro-to-Node.js-Exercises