javascript 让 express.js 显示公共文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17449475/
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-10-27 08:23:20  来源:igfitidea点击:

Getting express.js to show a public folder

javascriptnode.jsexpress

提问by Spentacular

I've recently built a quick one page app using express.js, and this is really my first js framework (actually, my first js project, so I'm really new to this). I've got a subscription to the new typography.com cloud fonts, and I'm having trouble locating the "fonts" folder that I place in the public folder. Is there a way I need to add the folder and specify a route?

我最近使用 express.js 构建了一个快速的单页应用程序,这确实是我的第一个 js 框架(实际上,我的第一个 js 项目,所以我对此很陌生)。我订阅了新的typography.com 云字体,但无法找到放置在公共文件夹中的“字体”文件夹。有没有办法添加文件夹并指定路线?

Here's my app.js file:

这是我的 app.js 文件:

/**
 * Module dependencies.
 */

var express = require('express'),
    routes = require('./routes'),
    user = require('./routes/user'),
    http = require('http'),
    path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static('public'));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

I haven't made any changes to the routes at all, so they are just default.

我根本没有对路由进行任何更改,因此它们只是默认值。

回答by moka

Please use express.staticsetting:

请使用express.static设置:

app.use(express.static(process.cwd() + '/public'));

And place your fontsfolder in that publicfolder.

并将您的fonts文件夹放在该public文件夹中。

回答by Aurélien Thieriot

If you are using Heroku, you may want to look at this thread: Deploy Nodejs on Heroku fails serving static files located in subfolders

如果您正在使用 Heroku,您可能需要查看此线程:在 Heroku 上部署 Nodejs 无法提供位于子文件夹中的静态文件

The guy explain that he struggled with "__dirname" until he specified the last version of NPM in his package.json:

这家伙解释说,他一直在努力解决“__dirname”问题,直到他在 package.json 中指定了最新版本的 NPM:

"engines": {
    "node": "0.10.11",
    "npm": "1.2.25"
} 

If that doesn't work, you might try:

如果这不起作用,您可以尝试:

// At the top of your web.js
process.env.PWD = process.cwd()

// Then
app.use(express.static(process.env.PWD + '/public'));

Instead of "__dirname"

而不是“__dirname”

Though, all that is probably useless if you already struggle localy.

但是,如果您已经在本地挣扎,那么所有这些都可能毫无用处。