Deno 简单静态 CRUD 示例

Deno Simple Static CRUD Example

appears 目前 Deno mysql driver 还不支持密码验证。我刚刚在 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 headers?

路由器是本地路由器还是必须是 OAK 路由器?

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

我只是很难找到示例。

Is the router native or does it have to be something called OAK?

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


到 return 一个文件,你使用 Deno.open 其中 return 是一个 Reader,你可以将那个 Reader 传递给 body req.respond 的 属性,接受 ReaderstringUint8Array

以下示例将读取文件 {HTTP_METHOD}.json 和 return 其内容,将 Content-Type header 设置为 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 服务器级别有点低,您可能需要使用框架。

框架有很多例子。