Domanda

I currently am serving all my html right in my app.js/server.js file like this:

app.get('/', function(req, res) {
    res.render('index.html');
});
app.get('/about', function(req, res) {
    res.render('about.html');
});
app.get('/projects', function(req, res) {
    res.render('projects.html');
});

I imagine if I have 15+ html pages that this is probably not the best way to call them. Is there a better way to serve them from another file or location and using export or something to be able to call just one function or something on app.js. It might be what the routing is for but maybe I do not understand it too well.

(added more code that is in the same file)

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/public');

// used below code to render html files
app.engine('html', require('ejs').renderFile);

app.set('view engine', 'ejs');
app.use(express.favicon("public/img/favicon.ico"));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
È stato utile?

Soluzione

You could use the static middleware:

app.use("/", express.static(__dirname));

A server example:

var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/public'));
app.listen(3000, function() { console.log('listening')});

This is the file structure:

.
├── public
│   ├── a.html
│   ├── b.html
│   └── c.html
└── server.js

Documentation:

Altri suggerimenti

One idea would be to use a catch-all kind of route as the last route, like the following:

app.get('/:page', function(req, res) {
  res.sendfile(path.join(__dirname, 'public', 'pages', path.basename(req.params.page) + '.html'));
});

That would require that you put your .html files into public/pages/about.html, etc.

You might want to switch the order of the static file router so that static files get precedence over routes, too, unless you want that route catching things in the public folder, like this:

app

app.set('view engine', 'ejs');
app.use(express.favicon("public/img/favicon.ico"));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top