How can I return html or json with deno?
Asked Answered
P

1

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.

Perkins answered 5/6, 2020 at 7:1 Comment(0)
M
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;
  }
Millpond answered 5/6, 2020 at 9:8 Comment(4)
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"Perkins
check the updated answer, use: this.response.headers.set("Content-Type", "text/html"); or application/json depending on the route.Millpond
Perfect thanks, and if I want to return a full html page with icon and everything else rather than a simple textPerkins
a "full html page" is simple text. If you want to serve static content such as images, check drash.land/docs/#/tutorials/servers/serving-static-pathsMillpond

© 2022 - 2024 — McMap. All rights reserved.