让Express提供默认页面的最简单方法是? [英] simplest way to have Express serve a default page?
问题描述
我正在使用它来将Node.js/Express设置为基本的Web服务器-它仅提供一组静态页面,而无需任何其他处理.我希望它在浏览器获取没有任何文件名的站点时始终提供/default.html.
I'm using this to have Node.js/Express setup as a rudimentary web server - it just serves a set of static pages without any other processing. I'd like it to always serve /default.html when a browser fetches the site without any filename.
var express = require("express");
var app = express();
var port = process.env.PORT || 5000;
app.configure(function(){
app.use(express.bodyParser());
});
app.use(express.logger());
app.use(express.static(__dirname ));
app.listen(port, function() {
console.log("Listening on " + port);
});
我尝试使用res.sendfile和res.redirect,但是没有成功;我显然丢失了一些东西,因为最终出现没有方法"错误.
I've tried using res.sendfile and res.redirect, but without much success; I'm obviously missing something as I end up with a 'has no method' error.
您说什么才是实现我的目标的最简单方法?
What would you say is the simplest way of achieving my goal?
推荐答案
您可以执行以下操作.假设它是一个相对于.js文件的html文件:
You could do something like this. Assuming its an html file that is relative to the .js file:
app.get('/', function(req, res){
res.sendfile('default.html', { root: __dirname + "/relative_path_of_file" } );
});
这篇关于让Express提供默认页面的最简单方法是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!