栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Express将整个文件夹内容发送到客户端

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Express将整个文件夹内容发送到客户端

您将无法使用发送多个文件

res.sendFile
。您可以在此处执行的最直接的操作是:

将您的

index.html
文件和
html5game
目录放入某个通用目录,例如
html
,并将其放在您的Node.js程序所在的位置。目录布局的示例为:

/home/you/yourapp:- app.js (your node program)- package.json (your package.json etc)- html (a new directory)  - index.html (your main html to serve)  - html5game (the directory with other files)    - (other files)

现在,在您的Node程序中,您可以使用如下代码:

var path = require('path');var express = require('express');var app = express();var htmlPath = path.join(__dirname, 'html');app.use(express.static(htmlPath));var server = app.listen(3000, function () {    var host = 'localhost';    var port = server.address().port;    console.log('listening on http://'+host+':'+port+'/');});

这将

index.html
在以下地址上提供您所有文件(包括)的地址:

  • http:// localhost:3000 /(您的
    index.html
  • http:// localhost:3000 / html5game / xxx.js(您的资产)

当然,您仍然需要确保

index.html
正确引用文件中的资产,例如:

<script src="/html5game/xxx.js"></script>

在上述示例布局的情况下。

index.html
通常会调用包含您的静态资产(您拥有)的顶层目录
static
public
或者
html
,只要您在调用中使用正确的路径,就可以随意调用它
express.static()

如果您想在根目录路径以外的其他路径中使用游戏,则可以将其指定为

app.use
。例如,如果您更改此设置:

app.use(express.static(htmlPath));

对此:

app.use('/game', express.static(htmlPath));

然后代替这些URL:

  • http:// localhost:3000 /(您的
    index.html
  • http:// localhost:3000 / html5game / xxx.js(您的资产)

这些网址将改为可用:

  • http:// localhost:3000 / game /(您的
    index.html
  • http:// localhost:3000 / game / html5game / xxx.js(您的资产)

这里有很多问题与使用Express提供静态文件有关,因此我制作了一个工作示例并将其发布在GitHub上,以便人们可以有一个工作的起点并从那里开始:

  • https://github.com/rsp/node-express-static-example


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/448451.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号