Deviopath › Node.js

Content Negotiation

Medium · HTTP

Express res.format() and req.accepts() pick a response type from the Accept header. Write negotiate(accept, available) that returns the best type from available, or null.

- accept is a comma-separated list like "text/html, application/json;q=0.9, */*;q=0.1". Each range may have a q (quality) parameter, default 1. Ignore other parameters and spaces. Compare types case-insensitively. An empty accept means */*.

- For each available type, find the MOST SPECIFIC range that matches it: an exact match beats type/*, which beats */*. That range's q is the type's quality, even if a less specific range has a higher q. (If several ranges are equally specific, use the first.)

- Types with no matching range, or quality 0, are not acceptable.

- Return the acceptable type with the highest quality, written as in available. On a tie, the one listed first in available wins.

(Simplified: the negotiator package used by Express also compares media type parameters and has extra tie-break rules.)

Next: Sort Semantic Versions