ExpressJS tutorial: GET, POST, JSON, HTML forms, 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" })
})

You can put express.json() in second parameter in an array in app.post() so the JSON middlewear only applies to that route.


We can create a route that gives us an HTML form. Note the nested style of the 'client' parameters in the form.

app.get("/htmlform", (req, res) => {
  res.send(`
    <form action="/htmlform" method="post">
      <input name="client[name][first]">
      <input name="client[name][second]">
      <button type="submit">press me<button>
    <form>
  `)
})

Now we can use express.urlencoded() in a post route to parse data from the HTML form. (From express 4.0 we no longer need to specify extended: true to allow nested HTML form parameters)

app.post("/htmlform", [express.urlencoded()], (req, res) => {
  res.send(req.body)
})

If we don't want to embed the HTML in our javascript file, we can put the HTML into an external file and use res.sendFile("__dirname" + "/yourfile.html"). __dirname is an internal nodejs variable that points to the directory where node was started.

Finally, if we go to http://localhost:3000/htmlform and fill in the form then press the button our post route will output something like:

{"client":
  {"name":
    {"first":"craig","second":"david"}
  }
}

If you want to redirect to another page, sending of res.send() for example, you can issue res.redirect("/another_route") to send return with a 302 request and a GET request to another_route.

nodejs

Edit on github
comments powered by Disqus
Click me