Lolix Dudu
Lolix Dudu

Reputation: 313

How can I return html or json with deno?

I would like to know if a Deno app can return json or a web page depending on the url. If so, which response type would I use? I know for json it's (I'm using Drash):

response_output: "application/json"

(for Drash.Http.Server)

Can I add something to allow returning a web page and, if so, how?

I know to return json it's like this:

this.response.body = myjson;
return this.response;

How can I do the same thing to return a web page?

Thanks for your answers.

Upvotes: 4

Views: 1979

Answers (1)

Marcos Casagrande
Marcos Casagrande

Reputation: 40444

use response_output with text/html

import { Drash } from "https://deno.land/x/drash/mod.ts";

class HomeResource extends Drash.Http.Resource {

  static paths = ["/"];

  public GET() {
    this.response.body = "GET request received!";
    if (this.request.accepts("text/html")) {
      // Your HTML here
      this.response.body = "<body>GET request received!</body>";
    }
    return this.response;
  }
}

const server = new Drash.Http.Server({
  response_output: "text/html",
  resources: [HomeResource],
});

response_output sets the default Content-Type, but you can change it on a specific route by doing:

this.response.headers.set("Content-Type", "text/html");
 public GET() {
    this.response.headers.set("Content-Type", "application/json");
    this.response.body = JSON.stringify({ foo: 'bar' });
    if (this.request.accepts("text/html")) {
      this.response.headers.set("Content-Type", "text/html");
      this.response.body = "<body>GET request received!</body>";
    }
    return this.response;
  }

Upvotes: 3

Related Questions