node.js/express:发送静态文件(如果存在) [英] node.js/express: Sending static files if they exist

查看:18
本文介绍了node.js/express:发送静态文件(如果存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to serve html files from a folder if they exist, otherwise fallback to the dynamic app.

目前我使用类似的东西:

currently I use something like:

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'));

我怎样才能做到这一点?

How can I achieve this?

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

Some tutorials use a module called connect. If it's the most elegant solution to my problem, how can I integrate connect to my current code?

推荐答案

你不需要做任何特别的事情.

You don't have to do anything special.

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

i'm assuming the WebContent folder is in the root.

如果您的所有静态内容都在您所展示的同一个基本文件夹中,您就不必多次指定它.

And if all your static content are in the same base folder like you've shown, you don't have to specify it multiple times.

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

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

if you have a file called file.html in the WebContent folder you can now access it via the url i.e. localhost:4444/file.html

这篇关于node.js/express:发送静态文件(如果存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆