Express.js Basics

Advertisement

Advertisement

Intro

This is a quick overview of a very simple express.js app.

Installation

npm install --save express ejs

The ejs package is for simple HTML templates.

Use auto-generated project template

Read more at https://expressjs.com/en/starter/generator.html.

npx express-generator

Build your own project structure from scratch

Project structure:

./app.js
./templates/index.html
./public/global.css

app.js:

// Run with `node app.js`
const path = require('path')
const express = require('express')

/*********************************
 * SETUP                         *
 *********************************/

const app = express()
const port = 3000

// Serve static files from public/
app.use('/static', express.static(path.join(__dirname, 'public')))
// Set template engine
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'templates'))  // EJS HTML Templates dir


/********************************
 * PAGES                        *
 ********************************/

app.get('/', (req, res) => {
    res.render('index', { title: 'hello' });
})


/********************************
 * RUN                         *
 *******************************/

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

templates/index.html:

<html>
    <head>
        <link rel="stylesheet" href="/static/global.css">
    </head>
    <body>
        <h1><%= title %></h1>
    </body>
</html>

Getting query parameters

Use the query property on the request object.

// For url:  /?thekey=something
app.get('/', (req, res) => {
    console.log(req.query.thekey)

})

References

Advertisement

Advertisement