Now that we have seen the first steps in working with Express,
let us look at the core process, routing.
If we have left the app.js, and the
bin/www alone, they are not so interesting at this
point. So let us combine two aspects from lesson 9 in
your textbook. Please notice, that I am using a, if you will,
real Express project, and the the somewhat
artificial from the books lesson.
myg91/routers/index.js
const worldControllers = require("../controllers/worldControllers");
const express = require('express');
const router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) { // route
res.render('index', { title: 'Express' }); // direct response with view
});
router.get("/items/:vegetable", function(req, res, next) { // route
let veg = req.params.vegetable; // handling before
res.send(`This is the page for ${veg}`); // response
});
router.get('/contact', function(req, res, next) { // route
res.render('contact', { title: 'Express Contacts' }); // direct response with view
});
router.post("/contact", function(req, res, next) { // route
console.log(req.body); // handling before
res.send("This page will be handling contacts"); // response
});
/*
* A couple of extra routes as hints, not used in myg91
*/
router.get("/country/:country", function(req, res, next) { // route with country name
let country = worldControllers.retrieveCountry(req.params.country); // get data from
res.render("country", country);
});
router.get("/countryData", function(req, res, next) { // route to country form page
res.render("countryData", {});
});
router.post("/countryData", function(req, res, next) { // route with country data
worldControllers.insertCountry(req, res); // handling before
});
module.exports = router;
In order to test one of the two homemade routes, we have borrowed the contact form from a previous project.
extends layout
block content
h1 Enter Your To Do Here
form(action='/contact' method='post')
table
tr
td BrugerId:
td
input(type='text' name='subject', required)
tr
td Message:
td
textarea(rows='4' cols='60' name='message' placeholder='enter text here', required)
tr
td Name:
td
input(type='text' name='name', required)
tr
td Email:
td
input(type='email' name='email', required)
tr
td
td
input(type='submit' value='Go')
Just for understanding, the following example is included here. We will talk about it later.
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
header
nav
ul
li
a(href="/") Home
li
a(href="/contact") Contact
li
a(href="/items/cucumbers") Cucumbers
li
a(href="/items/aubergines") Egg Plants
li
a(href="/items/artichokes") Artichokes
block content
On your CLI do npm start to start the server.
Then go to your browser and test each of the following
urls.
Check the browser screen as well as the console log in each case.