4

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.

Dillon
  • 1,394
  • 1
  • 11
  • 25
Lolix Dudu
  • 313
  • 2
  • 15

1 Answers1

3

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;
  }
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
  • Ok but here the server can only return html no ? How can I return json and html depending of the ressource ? Like have `response_output:"text/html" and "application/json"` – Lolix Dudu Jun 05 '20 at 09:26
  • check the updated answer, use: `this.response.headers.set("Content-Type", "text/html");` or `application/json` depending on the route. – Marcos Casagrande Jun 05 '20 at 09:33
  • Perfect thanks, and if I want to return a full html page with icon and everything else rather than a simple text – Lolix Dudu Jun 05 '20 at 10:15
  • a "full html page" is simple text. If you want to serve static content such as images, check https://drash.land/docs/#/tutorials/servers/serving-static-paths – Marcos Casagrande Jun 05 '20 at 10:18