【问题标题】:How can I return html or json with deno?如何使用 deno 返回 html 或 json?
【发布时间】:2020-08-23 01:21:46
【问题描述】:

我想知道 Deno 应用程序是否可以根据 url 返回 json 或网页。如果是这样,我会使用哪种响应类型?我知道 json 是(我正在使用 Drash):

response_output: "application/json"

(对于 Drash.Http.Server)

我可以添加一些内容以允许返回网页吗?如果可以,如何添加?

我知道返回json是这样的:

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

我怎样才能做同样的事情来返回一个网页?

感谢您的回答。

【问题讨论】:

    标签: deno


    【解决方案1】:

    使用response_outputtext/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 设置默认的Content-Type,但您可以通过以下方式在特定路由上更改它:

    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;
      }
    

    【讨论】:

    • 好的,但是这里服务器只能返回 html 不?如何根据资源返回 json 和 html ?喜欢有response_output:"text/html" and "application/json"
    • 查看更新后的答案,根据路线使用:this.response.headers.set("Content-Type", "text/html");application/json
    • 非常感谢,如果我想返回带有图标和其他所有内容的完整 html 页面,而不是简单的文本
    • 一个“完整的 html 页面”是简单的文本。如果您想提供图片等静态内容,请查看drash.land/docs/#/tutorials/servers/serving-static-paths
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    相关资源
    最近更新 更多