如何使用 deno return html 或 json?
How can I return html or json with deno?
我想知道 Deno 应用程序是否可以 return json 或取决于 url 的网页。如果是这样,我会使用哪种响应类型?我知道 json 是(我正在使用 Drash):
response_output: "application/json"
(对于 Drash.Http.Server)
我可以添加一些内容以允许 return 浏览网页吗?如果可以,如何添加?
我知道 return json 是这样的:
this.response.body = myjson;
return this.response;
如何对 return 网页执行相同的操作?
感谢您的回答。
将 response_output
与 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
设置默认值 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;
}
我想知道 Deno 应用程序是否可以 return json 或取决于 url 的网页。如果是这样,我会使用哪种响应类型?我知道 json 是(我正在使用 Drash):
response_output: "application/json"
(对于 Drash.Http.Server)
我可以添加一些内容以允许 return 浏览网页吗?如果可以,如何添加?
我知道 return json 是这样的:
this.response.body = myjson;
return this.response;
如何对 return 网页执行相同的操作?
感谢您的回答。
将 response_output
与 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
设置默认值 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;
}