Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/ayonli_jsext/esm/http.js>suggestResponseType

A JavaScript extension package for building strong and modern applications.
Latest
function suggestResponseType
import { suggestResponseType } from "https://deno.land/x/ayonli_jsext@v0.9.72/esm/http.js";

Gets the suggested response type for the request.

This function checks the Accept or the Content-Type header of the request, or the request method, or other factors to determine the most suitable response type for the client.

For example, when requesting an article which is stored in markdown, the server can respond an HTML page for the browser, a plain text for the terminal, or a JSON object for the API client.

This function returns the following response types:

  • text: plain text content (default)
  • html: an HTML page
  • xml: an XML document
  • json: a JSON object
  • stream: text stream or binary stream, depending on the use case
  • none: no content should be sent, such as for a HEAD request

Examples

Example 1

import { suggestResponseType } from "@ayonli/jsext/http";

export default {
    async fetch(req: Request) {
        const type = suggestResponseType(req);

        if (type === "text") {
             return new Response("Hello, World!");
        } else if (type === "html") {
             return new Response("<h1>Hello, World!</h1>", {
                 headers: { "Content-Type": "text/html" },
             });
        } else if (type === "xml") {
             return new Response("<xml><message>Hello, World!</message></xml>", {
                 headers: { "Content-Type": "application/xml" },
             });
        } else if (type === "json") {
             return new Response(JSON.stringify({ message: "Hello, World!" }), {
                 headers: { "Content-Type": "application/json" },
             });
        } else {
            return new Response(null, { status: 204 });
        }
    }
}