Express

Web Frameworks

Web frameworks can be very featureful:

  • providing everything for you from database access to templating…
  • and even dictating your project layout
  • (these tend to be larger, and occasionally more complex)


Web frameworks can also be very minimal:

  • only providing a small amount of core functionality
  • … and leaving other features to be integrated piecemeal as needed
  • (these tend to be smaller, and more bare bones)


Web frameworks can generally be categorized in this manner, or fall somewhere inbetween.

A Simple Express Program

Hello World

import express from 'express';
const app = express();

app.get('/', function(req, res){
	res.send('hello');
});

app.listen(3000);
console.log('Started server on port 3000');
 

Another URL

Let's try adding another url. The URL should be /faq. →

app.get('/faq', function(req, res) {
	res.send('you has q, i has answer');
});
 

Path and Static Middleware

Use the path module to create a path that specifies where your static files are located.

// bring in the path module
import path from 'path';
import url from 'url';

// create a cross-platform compatible path name (don't just use public)
const basePath = path.dirname(url.fileURLToPath(import.meta.url));
const publicPath = path.resolve(basePath, "public");

Use the built-in static files middleware to serve up any file in publicPath

app.use(express.static(publicPath));
 

Templating

There are many templating solutions that we can use, both on the server side and the client side.

  • jade/pug comes with express, and it has a meta language for writing html!
    • terse syntax based on indentation (no closing tags!)
    • very quick to write, but you have to learn a lot more new syntax
  • handlebars is based off of a basic templating language called mustache
    • it's basically just html
    • with some special tokens for inserting data
 

We'll be using handlebars.

(slightly less to learn … but definitely feel free to use jade/pug instead)

 

Handlebars

First, install the express handlebars module:

npm install hbs --save

 

And in your code, bring in handlebars for templating:

app.set('view engine', 'hbs');

 

Render a template!

res.render('index', { "greeting":"HELLLOOOO" });
 

Layouts

In views/layout.hbs …

(Notice 3 curly braces!)

<!-- surrounding html -->
{{{ body }}}
<!-- surrounding html -->
 

Templates

In views/viewname.hbs … drop in your content

{{ greeting }} world!
 
 
posted @ 2023-03-01 23:52  M1stF0rest  阅读(32)  评论(0编辑  收藏  举报