Getting express.js to show a public folder

跟風遠走 提交于 2020-01-23 09:57:33

问题


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.


回答1:


Please use express.static setting:

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

And place your fonts folder in that public folder.




回答2:


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.



来源:https://stackoverflow.com/questions/17449475/getting-express-js-to-show-a-public-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!