Content negotiation

The Koa request object includes some helper methods for content negotiation, powered by accepts and negotiator. These include the following:

  • request.accepts(types...): This checks whether the given types are acceptable, then returns the best match when true. It returns false if the types are not acceptable. The types value may be a comma separated list of mime type strings or extension names, or an array. This is shown in the following block:
      // Accept: text/*, application/json
ctx.accepts('text/html');
// => "text/html"
ctx.accepts(['html', 'json']);
// => "json"
ctx.accepts('png');
// => false
  • request.acceptsEncodings(encodings): This checks whether the encodings supplied are acceptable and returns the best match when true. It returns false when no match exists. It returns all the accepted encodings as an array when no argument is given, as shown here:
      // Accept-Encoding: gzip, deflate, br
ctx.acceptsEncodings()
// => [ 'gzip', 'deflate', 'br', 'identity' ]

  • request.acceptsLanguages(langs): This checks whether the langs supplied are accepted and returns the best match when true. It returns false when no match exists. It returns all the accepted languages as an array when no argument is given:
      // Accept-Language: en-US,en;q=0.9,cy;q=0.8

console.log(ctx.acceptsLanguages('en'));
// => en

console.log(ctx.acceptsLanguages('en', 'cy'));
// => en

console.log(ctx.acceptsLanguages(['en', 'cy']));
// => en

ctx.acceptsLanguages();
// => [ 'en-US', 'en', 'cy' ]

console.log(ctx.acceptsLanguages('es'));
// => false
  • request.idempotent: This returns a Boolean specifying whether the request is idempotent or not.
A request is idempotent if multiple identical requests with that method have the same effect on the server as the effect for a single such request.
  • request.socket: This returns the request socket.
  • request.get(field): This returns the request header value for a specified field:
      // Accept-Language: en-US,en;q=0.9,cy;q=0.8

ctx.request.get('Accept-Language');
// => en-US,en;q=0.9,cy;q=0.8
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.22.169