简体   繁体   中英

Getting express.js to show a public folder

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?

Here's my app.js file:

/**
 * 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.

Please use express.static setting:

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

And place your fonts folder in that public folder.

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

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

"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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM