如何使用 serveFile 在 Deno 中提供文件?

时间:2021-03-29 15:34:48

标签: typescript localhost deno

我的脚本如下,编译没有错误,假设提供 index.html,但是当页面显示它正在加载时,没有任何东西发送到浏览器。

import { serve } from "https://deno.land/std@0.91.0/http/server.ts";
import { serveFile } from 'https://deno.land/std@0.91.0/http/file_server.ts';

const server = serve({ port: 8000 });
console.log("http://localhost:8000/");

for await (const req of server) {
  console.log(req.url);
  if(req.url === '/')
    await serveFile(req, 'index.html');
}

那么为什么在这种情况下 serveFile 不起作用?

1 个答案:

答案 0 :(得分:1)

serveFile 的调用仅创建一个 Response(状态、标题、正文)但不会发送它。

您必须通过单独调用 req.respond() 来发送它:

import { serve } from "https://deno.land/std@0.91.0/http/server.ts";
import { serveFile } from 'https://deno.land/std@0.91.0/http/file_server.ts';

const server = serve({ port: 8000 });
console.log("http://localhost:8000/");

for await (const req of server) {
  console.log(req.url);
  if(req.url === '/') {
    const response = await serveFile(req, 'index.html');
    req.respond(response)
  }
}
相关问题