Express

4 flashcards · Programming Languages · by lakesare

  1. POST /user/:name?order=desc with body { hi: 20 } How to get :name, ?order, and hi?

    const name = request.params.name; const order = request.query.order; const hi = request.body.hi; For example, if you have the route /user/:name, then the “name” property is available as req.params.name. Links: https://expressjs.com/en/api.html#req.params

  2. The true callback in an Express middleware chain isn't actually next, as you might assume, but res.end(). Any request that is handled must, at some point, call this function (either directly or indirectly) to say that the request has been handled. When you call next() in your middelware, you're passing on the responsibility of calling res.end() to the middleware further down the middleware chain.

    Middleware functions can perform the following tasks: Execute any code. Make changes to the request and the response objects. End the request-response cycle. Call the next middleware in the stack.

  3. If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

    next(err) will skip all remaining handlers in the chain except for those that are set up to handle errors as described above.

  4. For synchronous functions (error, request, response, next) middleware will get called automatically: app.get("/", function (req, res) { throw new Error("BROKEN"); }); What about errors in promises and callbacks?

    Then we need to call next() with an error object! app.get("/", function (req, res, next) { fs.readFile("/file-does-not-exist", function (err, data) { if (err) { next(err); // Pass errors to Express. } else { res.send(data); } }); });