Joshua's Docs - Express JS Notes

Great cheatsheets

Quick Ref Table

Side Thing Description Relev type sig
Request req.params Captures named params, made explicit in route signature. `{[index: string]: string
Request req.query Captures QueryString key-pair vals. `{[index: string]: string
Request req.body Captures body payload key-pairs

Requires body parsing middleware
{[index: string]: any}

How do I...

  • Capture variable through route?
    • Use :var syntax in route, then access through injected req.params
      app.get('/users/:userId', (req, res) => {
      	const userId = req.params.userId;
    • Or through actual request payload, with req.body (if using body-parser)
    • Or through query params with req.query.{queryParam}
  • Inject a variable into the route?
    • You probably want to use middleware
    • Actually very easy to write your own with just a few lines of code...
  • Capture a parameter and check if it was used in the request?
    • GET (QueryString)
      • Use req.query, which returns object of key/pair values corresponding to querystring.
      • Check for valid value through standard JS logic; e.g., if you are expecting a string for /?name={name}, maybe do !!
    • POST (Body)
      • Basically same as GET, but use req.body, to access POST body params (assuming you switch to body with POST)
      • Requires body-parsing middleware
    • Named param in route
      • If you are capturing parameters explicitly as part of the route, you can use req.params to get the captured value
      • Example, if route is /book/:id, you can get ID through
    • ALL
      • If you want to accept the same parameter, and allow it to be passed via any of the three methods (QueryString, Body, or Named Params), that is a little trickier
      • There used to be an API method for this, req.param({name}, {defaultValue}), but it was deprecated.
      • If you really need this, you could easily write your own wrapper method to check all three inputs and validate, and/or take a look at the original code, here.
      • Relevant S/O thread

Param types

The built-in query string parser in Express does not infer types. For example, you might be tempted to think that if your request looks like /?name=joe&age=13, then would be typeof string, and req.query.age would be typeof number. This is wrong. They are all inferred as strings.

In addition, since req.query is an object, if you try to query a param that was not provided, you will get back undefined, not an empty string.

All of the above is also true for req.params, but not for req.body, since if JSON is passed via request, then the types are preserved without any special parsing needed

Common Issues

    • This indicates that you are basically trying to send a response back multiple times, or trying to set headers on a response after it has already been sent
    • A very common reason for this is forgetting to return after sending a response, so your code continues and tries to send a second response.
  • BadRequestError: request aborted
    • This is kind of a generic error, indicating that something interrupted the process of reading in the request
    • Is likely to happen with the body-parser plugin
    • I personally hit this with mismatched Content-Length headers - where this error will throw if I send a request with an explicit Content-Length header that doesn't match the body size
      • Easy to accidentally do this if you are cloning Postman requests
Markdown Source Last Updated:
Mon Oct 26 2020 13:36:33 GMT+0000 (Coordinated Universal Time)
Markdown Source Created:
Mon Oct 26 2020 13:34:56 GMT+0000 (Coordinated Universal Time)
© 2024 Joshua Tzucker, Built with Gatsby