ExpressJS quick guide: GET, POST, JSON and query & url parameters

npm install express installs node's HTTP framework. express = require('express') gets a reference to express. app = express() creates an instance. app.listen(3000, _ => {}) starts it.

app.get(urlstring, (request, response) => {}) creates a GET route, which is passed a request and response parameter.

request.query is an object with all the query parameters. request.params is an object with all the url parameters, as defined with the syntax :variable_name in the url string.

response.send() returns a string to the client. response.json() will return a json object to the client with the relevant response headers.

const express = require('express')
const app = express()
app.listen(3000, _ => console.log("started on 3000"))

app.get("/:username/:place", (req, res) => {
  var username = req.params.username
  var place = req.params.place
  var debug = req.query.debug
  res.send(`hi ${username} at ${place} with debug status ${debug}`)
})

You can hit that with http://localhost:3000/chris/cross?debug=hell%20yes.

app.use(express.json()) will allow you to access POSTed JSON through the request.body object. app.post() will create a POST route. Then we can access that body object.

const express = require('express')
const app = express()
app.use(express.json())
app.listen(3000, _ => console.log("started on 3000"))

app.post("/post", (req, res) => {
  res.send("sent name via post" + req.body.name)
})

You can access that new endpoint through

fetch("http://localhost:3000/post", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ "name": "Christopher Cross" })
})
nodejs

Javascript: A quick introduction to __proto__ and prototype

Javascript looks up a property on an object, student in our example. Javascript first looks at all the properties on student. If it doesn't find it, it looks at the properties on the __proto__ object, which is itself a property on student.

var school = {
  school_name: "Handsome boy modelling school"
}

var student = {
  name: "Nathaniel Merryweather"
}

student.name // outputs "Nathaniel Merryweather"
// student.school_name     will be undefined

student.__proto__ = school

console.log(student.name, student.school_name)
// outputs "Nathaniel Merryweather", "Handsome boy modelling school"

If we have lots of students, making a new object every time will become boring. We can use a function with new and this inside the function to make it easier.

var school = {
  school_name: "Handsome boy modelling school"
}

function Student(name) {
  this.name = name
}

var nathanial = new Student("Nathaniel Merryweather")
nathanial.__proto__ = school
console.log(nathanial.name, nathanial.school_name)

var chad = new Student("Chad Baker")
chad.__proto__ = school
console.log(chad.name, chad.school_name)

But we still have to manually add __proto__ to each object. We can make that easier by setting Student's prototype object to be our student object: it sets the object's __proto__ property when we make a new object.

var school = {
  school_name: "Handsome boy modelling school"
}

function Student(name) {
  this.name = name
}
Student.prototype = school

var nathanial = new Student("Nathaniel Merryweather")
console.log(nathanial.name, nathanial.school_name)

var chad = new Student("Chad Baker")
console.log(chad.name, chad.school_name)

Javascript is full of objects, Date as one example. All objects have properties. You can, at runtime, add new properties to all instances of any object. You do this by adding a new property to the prototype object.

var now = new Date()

now.custom_property // outputs undefined

Date.prototype.custom_property = "I am a custom property"

now.custom_property // outputs the above
javascript

Get extension and body from base64 encoded image

Base 64 images start with data:image/. After this comes the image type. Then ;base64,. And finally the base64 encoded data.

We can use that information to find the file extension between data:image/ and ;base64,.

function base64encoded_image_extension_and_body(data) {
  var base64_part = data.search(/;base64,/)
  var ext = data.substring("data:image/".length, base64_part)
  var body = data.substr(base64_part + 8) // ;base64, is 8 chars
  return { body, ext }
}
javascript

Get dimensions (and scale) an image in javascript

Load an image using new Image() and when onload is called the image will have width and height properties.

You can divide a max height by the actual height, if it's bigger, to get a ratio of the excess size, and multiple the height and width by that to resize the image.

We do all this, and wrap it in a Promise, below.

function dimensions_from_image(url, max_height=300, 
  max_width=600) {
  return new Promise((res, rej) => {
    var img = new Image();
    img.onerror = e => rej(e)
    img.onload = () => {
      var height = img.height;
      var width = img.width;
      if (height >= max_height) {
        var ratio = max_height / height
        height = height * ratio
        width = width * ratio
      }
      if (width >= max_width) {
        var ratio = max_width / width
        width = width * ratio
        height = height * ratio
      }
      res([width, height])
    }
    img.src = url
  })
}

It's called via

dimensions_from_image("the url")
.then(([width, height]) => {
  // do something
})
.catch(e => {
  // uh oh
})
javascript

HTML/Javascript: Drag and drop images and files

HTML5 has a drag and drop implementation. It's used to drag images from other websites and to drag images from our filesystem.

<div id="drop" 
   style="height: 200px; width: 200px; background: blue;" 
   ondragenter="ondragenter" 
   ondragleave="ondragleave">
</div>

We specify two event handlers, ondragenter and ondragleave. These will highlight our div when the user drags an image over it.

These are global handlers for blog-post convenience. I've placed them on our div and made them global functions.

<script>
  var drop = document.querySelector("#drop")
  ondragenter = ev => {
    if (ev.target.id == "drop") 
      ev.target.style.backgroundColor = "red"
  }
  ondragleave = ev => {
    if (ev.target.id == "drop") 
      ev.target.style.backgroundColor = "blue"
  }
</script>

We need to make our div to accept images and files. It needs ondrop and ondropover. ondropover needs to return false or call event.preventDefault() to make the div a drop target. ondrop also needs to call event.preventDefault() and in that function all the magic happens.

<div id="drop" 
   style="height: 200px; width: 200px; background: blue;" 
   ondragenter="ondragenter" 
   ondragleave="ondragleave"
   ondrop="ondrop"
   ondragover="return false">
</div>
<script>
  var drop = document.querySelector("#drop")
  ondrop = ev => {
    ev.preventDefault()
    alert("You dragged something")
  }
  ondragenter = ev => {
    if (ev.target.id == "drop") 
      ev.target.style.backgroundColor = "red"
  }
  ondragleave = ev => {
    if (ev.target.id == "drop") 
      ev.target.style.backgroundColor = "blue"
  }
</script>

You can test it by trying to drag an image below.


In ondrop, we have an event that has a dataTransfer object. This has a files object that is full if the user dragged a file from their filesystem. You can upload this and each file object has a name property.

If it wasn't a file, we can call getData("text/html") on dataTransfer to get the html of what was dragged, make that into an element and run querySelector to get the img's src property, which could either be a file or a base64 encoded file.

Below is an expanded ondrop.

ondrop = ev => {
  ev.preventDefault()
  var html;
  if(ev.dataTransfer.files.length > 0) {
    var file = ev.dataTransfer.files[0]
    var form_data = new FormData()
    form_data.append("files[]", file)
    alert("Ready to upload some form data", file.name)
  } else if(html = ev.dataTransfer.getData("text/html")) {
    var img_ob = image_src_from_html(html)
    console.log(img_ob)
  } else {
    console.log("there wasn't any html or a filelist")
  }
}
function image_src_from_html(html) {
  var ret = {}
  var el = document.createElement("div")
  el.innerHTML = html
  var img = el.querySelector("img")
  if(!img) return ret
  var src = img.getAttribute("src")
  if(src.startsWith("data:image")) ret.urlencoded = src
  else ret.src = src
  return ret
}  
javascript html

Page 1 of 99
next
Click me