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

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

问题描述



目前我使用的东西如下:

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

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

//这里我想定义一个这样的规则:
//app.use(\"*.html,express.static(__ dirname +'/../WebContent/ * HTML'));

如何实现?



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

解决方案

你没有做任何特别的事情



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



如果所有静态内容都在与您所显示的相同的基本文件夹,您不必多次指定。

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

如果您在WebContent文件夹中有一个名为file.html的文件,您现在可以通过URL访问它即localhost:4444 / file.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?

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.

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

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天全站免登陆