// Express apps respond to HTTP requests via routing.
    
// Boilerplate Express.
const express = require('express');
const app = express();
app.listen(8000);

// app.all can handle all requests and next() will pass control
// to the next handler.
app.all('*', (req, res, next) => {
  console.log(`Handling ${req.path}`);
  next(); 
})

// This is a basic route.  
app.get('/get', (req, res) => {
  res.send('This is a basic route.');
});

// By default, Express sends replies with a 200 status code for "OK",
// but you can send any status code and message.
app.get('/getError', (req, res) => {
  res.statusMessage = 'This can be a custom message.';
  res.status(500).send('This is an error!');
});

// This parameter will match a single digit.
app.get('/get/:digit(\\d{1})', (req, res) => {
  let param = req.params.digit;
  res.send(`${param} is a single digit.`);
})

// This parameter will match a multiple digits.
app.get('/get/:digits(\\d+)', (req, res) => {
  let param = req.params.digits;
  res.send(`${param} is more than 1 digit.`);
})

// This route can match multiple parameters.
app.get('/get/:param1,:param2', (req, res) => {
  let {param1,param2} = req.params;
  res.send(`${param1} and ${param2} are 2 parameters.`);
})

// This route will match with anything else.
app.get('/get/:AnyParam', (req, res) => {
  let param = req.params.AnyParam;
  res.send(`The parameter is ${param}.`);
})


// This route can process a form submission.
app.post('/postForm',
  express.urlencoded({extended:false}),
  (req,res) => res.send(`You pressed ${req.body.button}`))



// This route can process JSON data.
app.post('/postJSON',
  express.json(),
  (req,res) => console.log(`Got ${JSON.stringify(req.body)}`))



// This route will send JSON data.
app.get('/getJSON',
  (req,res) => res.json({a:1, b:2, c:3}));



// This is the HTML with links to all of the above routes.
app.get('/', (req, res) => {
  res.send(`<pre>
  
<a href="/get">Make a basic GET request.</a><br />
  
<a href="/getError">Send an error.</a><br />
  
<a href="/get/1">/get/1</a><br />
  
<a href="/get/123">/get/123</a><br />
  
<a href="/get/abc,123">/get/abc,123</a><br />
  
<a href="/get/anything-else">/get/anything-else</a><br />
  
<form action="/postForm" method="post" style="border:1px solid red">
  A simple form.  
  <button name="button" value="yes" type="submit">Yes</button>
  <button name="button" value="no"  type="submit">No</button>
</form>

<button type="button" onclick="javascript:
 fetch('/postJSON',
  {method:'POST',
   headers:{'Content-Type':'application/json'},
   body:JSON.stringify({a:1,b:2})});">Post JSON</button>

<a href="/getJSON">Get JSON.</a><br />

</pre>`);
});




// https://sean.brunnock.com  1/2023