【问题标题】:Deno Simple Static CRUD ExampleDeno 简单静态 CRUD 示例
【发布时间】:2020-06-25 00:09:03
【问题描述】:

appears,当前 Deno 的 mysql 驱动程序尚不支持密码验证。我刚刚在 PHP 中完成了一个 API,并希望在 Deno 中看到一个相同的示例。

这与您从他们的网站上获得的示例一样多:

import { serve } from "https://deno.land/std@0.58.0/http/server.ts";
const s = serve({ port: 8000 });
console.log("http://localhost:8000/");
for await (const req of s) {
  req.respond({ body: "Hello World\n" });
}

我在哪里添加 JSON 标头?

路由器是原生的还是必须是称为 OAK 的东西?

您是否可以在此示例中添加静态 GET、POST、PUT DELETE,在每个相应的端点返回 post.json、get.json、put.json、delete.json 文件内容?

我只是很难找到例子。

【问题讨论】:

    标签: node.js deno


    【解决方案1】:

    路由器是原生的还是必须是称为 OAK 的东西?

    不,没有内置路由器。您可以使用 Oak 或其他 HTTP 框架。


    要返回一个文件,你可以使用Deno.open,它返回一个Reader,你可以将Reader传递给req.respondbody属性,它接受Readerstring或@ 987654330@.

    以下示例将读取文件{HTTP_METHOD}.json,并返回其内容,将Content-Type 标头设置为application/json

    import { serve } from "https://deno.land/std@0.58.0/http/server.ts";
    const s = serve({ port: 8000 });
    console.log("http://localhost:8000/");
    
    async function handleRequest(req) {
      try {
        const headers = new Headers({ 'Content-Type': 'application/json' });
        const file = await Deno.open(`./${req.method.toLowerCase()}.json`);
        await req.respond({ body: file, headers })
      } catch(e) {
        console.error(e);
        req.respond({ body: 'Internal Server Errror', status: 500 });
      }
    }
    
    for await (const req of s) {
      handleRequest(req);
    }
    

    std HTTP 服务器有点低级,你可能想使用框架。

    框架有很多例子。

    【讨论】:

    • 马科斯,这是一个很好的开始!好的。使用Deno.open 时,./ 指的是deno.exe 默认位置吗?基本上,我在 Deno 中的根目录是什么?
    • 出现错误`TS7006 [ERROR]:参数“req”隐含地具有“任何”类型。异步函数句柄请求(请求){`
    • 我举了一个 JS 例子,如果你使用的是 typescript,请设置正确的类型:ServerRequest
    • async function handleRequest(req: ServerRequest) {
    • 你必须导出类import { serve, ServerRequest } from "https://deno.land/std@0.58.0/http/server.ts";
    猜你喜欢
    • 2014-08-29
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 2011-08-31
    相关资源
    最近更新 更多