🪴 yshalsager's Digital Garden

Search

Search IconIcon to open search

Node.js Express

Last updated Nov 13, 2022

المعرفة:: NodeJS
الحالة:: #ملاحظة_مؤرشفة
المراجع:: The Complete Node.js Developer Course 3rd Edition, coggro’s Notes


1
npm install express  

# Getting Started

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// const express = require('express')  
// import express  
import express from 'express'  
  
// call express to start server  
const app = express()  
const port = 3000  
  
// .get takes route and fx for what to do  
// args are req object and res object  
app.get('/', (req, res) => {  
  // Send something back to user  
  res.send('Hello World!')  
})  
  
// Set the server to listen on a prescribed port  
app.listen(port, () => {  
  console.log(`Example app listening on port ${port}`)  
})  
1
2
3
4
5
  res.send(`<h1>Weather</h1>`)  
  res.send({  
    name: `Corey`,  
    age: 31,  
  })  

# Serving static files

1
2
3
4
import { join } from "path";  
  
// .. is one dir up  
console.log(`joined path`, path.join(__dirname, `..`, `/public`))  
1
2
const publicDirectoryPath = path.join(__dirname, '../public')  
app.use(express.static(publicDirectoryPath))  

# Dynamic Pages with Templating

1
app.set(`view engine`, `hbs`)  
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<html lang="en">  
  <head>  
    <meta charset="UTF-8" />  
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />  
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />  
    <title>Document</title>  
    <link rel="stylesheet" href="/styles/styles.css" />  
  </head>  
  <body>  
    <h1>{{ title }}</h1>  
    <p>{{ name }}</p>  
  
    <script src="/scripts/script.js"></script>  
  </body>  
</html>  
1
2
3
4
5
6
7
8
app.get(``, (req, res) => {  
  // first arg is view to render  
  // second arg is dynamic values to pass  
  res.render(`index`, {  
    title: `Weather App`,  
    name: `Andrew Mead`,  
  })  
})  

# Customizing Views and Partials Directories

1
2
const viewsPath = path.join(__dirname, '../templates/views');  
app.set('views', viewsPath);  
1
2
3
import hbs from "hbs";  
const partialsPath = path.join(__dirname, '../templates/partials');  
hbs.registerPartials(partialsPath);  

# Partials and Advanced Templating

1
2
3
4
5
6
7
8
<!-- <h1>Static Header.hbs Text</h1> -->  
<h1>{{title}}</h1>  
  
<div>  
    <a href="/">Weather</a>  
    <a href="/about">About</a>  
    <a href="/help">Help</a>  
</div>  
1
2
3
4
  <body>  
    {{>header}}  
    <p>{{ name }}</p>  
  </body>  

# Setting up 404 Pages

1
2
3
4
5
6
7
app.get(`/help/*`, (req, res) => {  
  res.send(`Help article not found`)  
})  
  
app.get(`*`, (req, res) => {  
  res.send(`Page not found`)  
})  

# Query Strings

1
2
3
4
// http://localhost:3000/products?search=games&rating=5  
app.get('/products', (req, res) => {  
  console.log(req.query) // {search: "games", rating: "5"}  
})  
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
app.get(`/products`, (req, res) => {  
  if (!req.query.search) {  
    return res.send({  
      error: `You must provide a search term`,  
    })  
  }  
  res.send({  
    products: [],  
  })  
})  
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
app.get(`/weather`, (req, res) => {  
  if (!req.query.address) {  
    return res.send({  
      error: `You must provide a location.`,  
    })  
  }  
  res.send({  
    forecast: `The weather forecast is that there will be weather whether or not you can weather it.`,  
    location: req.query.address,  
  })  
})