简体   繁体   English

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

[英]How to serve files in Deno using serveFile?

My script as follows, which compiles without errors, is suppose to serve index.html, however nothing is ever sent to the browser while the page is showing it's loading.我的脚本如下,它编译没有错误,假设服务于 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');
}

So why is serveFile not working in this instance?那么为什么 serveFile 在这种情况下不起作用呢?

The call to serveFile only creates a Response (status, headers, body) but doesn't send it.serveFile的调用只会创建一个Response (状态、标题、正文),但不会发送它。

You have to send it with a separate call to req.respond() :您必须单独调用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)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM