node.js/ express : Sending static files if they exist

标签 node.js express socket.io

我想从文件夹中提供 html 文件(如果存在),否则回退到动态应用。

目前我使用类似的东西:

var express = require('express');
var app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);

server.listen(4444);

app.use("/", express.static(__dirname + '/../WebContent/index.html'));
app.use("/styles", express.static(__dirname + '/../WebContent/styles'));
app.use("/script", express.static(__dirname + '/../WebContent/script'));

//here I would like to define a rule like this:
//app.use("*.html", express.static(__dirname + '/../WebContent/*html'));

我怎样才能做到这一点?

一些教程使用名为 connect 的模块。如果它是解决我的问题的最优雅的解决方案,我该如何将连接集成到我当前的代码中?

最佳答案

您不必做任何特别的事情。

我假设 WebContent 文件夹位于根目录中。

如果您所有的静态内容都在您显示的同一个基础文件夹中,则您不必多次指定它。

 app.use(express.static(__dirname + '/WebContent'));

如果您在 WebContent 文件夹中有一个名为 file.html 的文件,您现在可以通过 url 访问它,即 localhost:4444/file.html

关于node.js/ express : Sending static files if they exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14124924/

相关文章:

javascript - 在 promise 解决后调用函数,但 Jasmine 未通过测试。为什么?

javascript - 为什么 pm2 忽略了传递给 ecosystem.config.js 文件中 Node 的 --experimental-modules?

node.js - 错误 : Could not find browser revision 756035. 运行 "npm install"

node.js - 在C9 Cloud IDE 中运行Jade 模板有什么技巧?

javascript - Node.js - 错误 : Cannot find module 'config/chgpass'

javascript - 如何使用 post 参数重定向到外部 URL?

node.js - Mean Stack 应用程序中的部分页面渲染问题

laravel - net::ERR_CONNECTION_TIMED_OUT error in laravel echo with redis driver

javascript - 如何在客户端获取连接的 socket.id?

javascript - 在多个客户端 JavaScript 文件之间传递套接字