node.js 带有 express.js 的静态文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10434001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:39:16  来源:igfitidea点击:

static files with express.js

node.jsexpress

提问by user124114

I want to serve index.htmland /mediasubdirectory as static files. The index file should be served both at /index.htmland /URLs.

我想服务index.html/media子目录作为静态文件。索引文件应同时提供 at/index.html/URL。

I have

我有

web_server.use("/media", express.static(__dirname + '/media'));
web_server.use("/", express.static(__dirname));

but the second line apparently serves the entire __dirname, including all files in it (not just index.htmland media), which I don't want.

但第二行显然服务于整个__dirname,包括其中的所有文件(不仅仅是index.htmlmedia),这是我不想要的。

I also tried

我也试过

web_server.use("/", express.static(__dirname + '/index.html'));

but accessing the base URL /then leads to a request to web_server/index.html/index.html(double index.htmlcomponent), which of course fails.

但是访问基本 URL/会导致对web_server/index.html/index.html(双index.html组件)的请求,这当然会失败。

Any ideas?

有任何想法吗?



By the way, I could find absolutely no documentation in Express on this topic (static()+ its params)... frustrating. A doc link is also welcome.

顺便说一句,我在 Express 中绝对找不到关于这个主题的文档(static()+ 其参数)......令人沮丧。也欢迎提供文档链接。

采纳答案by abe

express.static()expects the first parameter to be a pathof a directory, not a filename. I would suggest creating another subdirectory to contain your index.htmland use that.

express.static()期望第一个参数是目录的路径,而不是文件名。我建议创建另一个子目录来包含您index.html并使用它。

Serving static files in Express documentation, or more detailed serve-staticdocumentation, including the default behavior of serving index.html:

在 Express文档更详细的serve-static文档中提供静态文件,包括服务的默认行为index.html

By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.

默认情况下,此模块将发送“index.html”文件以响应对目录的请求。要禁用此设置 false 或提供新索引,请按首选顺序传递字符串或数组。

回答by 250R

If you have this setup

如果你有这个设置

/app
   /public/index.html
   /media

Then this should get what you wanted

那么这应该得到你想要的

var express = require('express');
//var server = express.createServer();
// express.createServer()  is deprecated. 
var server = express(); // better instead
server.configure(function(){
  server.use('/media', express.static(__dirname + '/media'));
  server.use(express.static(__dirname + '/public'));
});

server.listen(3000);

The trick is leaving this line as last fallback

诀窍是将此行作为最后的后备

  server.use(express.static(__dirname + '/public'));

As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.

至于文档,由于 Express 使用了 connect 中间件,我发现直接查看 connect 源代码更容易。

For example this line shows that index.html is supported https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140

例如,这一行显示支持 index.html https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140

回答by ChrisCantrell

In the newest version of express the "createServer" is deprecated. This example works for me:

在最新版本的 express 中,不推荐使用“createServer”。这个例子对我有用:

var express = require('express');
var app = express();
var path = require('path');

//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); //  "public" off of current is root

app.listen(80);
console.log('Listening on port 80');

回答by xameeramir

res.sendFile& express.staticboth will work for this

res.sendFileexpress.static两者都适用于此

var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');

// viewed at http://localhost:8080
app.get('/', function(req, res) {
    res.sendFile(path.join(public, 'index.html'));
});

app.use('/', express.static(public));

app.listen(8080);

Where publicis the folder in which the client side code is

public客户端代码所在的文件夹在哪里

As suggestedby @ATOzTOAand clarified by@Vozzie, path.jointakes the paths to join as arguments, the +passes a single argument to path.

作为建议通过@ATOzTOA由澄清@Vozziepath.join采取的路径加入作为参数时,+通过一个单一的参数路径。

回答by rajmobiapp

const path = require('path');

const express = require('express');

const app = new express();
app.use(express.static('/media'));

app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'media/page/', 'index.html'));
});

app.listen(4000, () => {
    console.log('App listening on port 4000')
})

回答by Rejayi CS

npm install serve-index

npm 安装服务索引

var express    = require('express')
var serveIndex = require('serve-index')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
var port = process.env.PORT || 3000;
/**for files */
app.use(serveStatic(path.join(__dirname, 'public')));
/**for directory */
app.use('/', express.static('public'), serveIndex('public', {'icons': true}))

// Listen
app.listen(port,  function () {
  console.log('listening on port:',+ port );
})

回答by Pravin

use below inside your app.js

在你的 app.js 中使用下面

app.use(express.static('folderName'));

(folderName is folder which has files) - remember these assets are accessed direct through server path (i.e. http://localhost:3000/abc.png(where as abc.png is inside folderName folder)

(folderName 是包含文件的文件夹)-记住这些资产是通过服务器路径直接访问的(即http://localhost:3000/abc.png(其中 abc.png 在 folderName 文件夹中)