node.js express不返回默认页面
在此代码中node.js express不返回默认页面,node.js,express,Node.js,Express,在此代码中 var history = require('connect-history-api-fallback'); var express = require('express'); var path = require('path'); var app = express(); app.use(history({ index: 'Trading Inquiry/index.html' })); app.use(express.static(path.join(__dirname
var history = require('connect-history-api-fallback');
var express = require('express');
var path = require('path');
var app = express();
app.use(history({
index: 'Trading Inquiry/index.html'
}));
app.use(express.static(path.join(__dirname, 'Trading Inquiry')));
app.get('/', function (req, res) {
console.log(1);
res.sendFile('Trading Inquiry/index.html');
});
var server = app.listen(process.env.PORT || 3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('My site started at http://%s:%s', host, port);
});
我设置它,使链接是相对的文件夹交易查询。加上给定的ig/route,返回index.html文件,对于不匹配的路由,还返回index.html文件。然而,当我访问时,我得到了
但这是可行的
http://localhost:3000/index.html
有人知道怎么了吗
谢谢res.sendFile不使用快速公共路径,因此在发送文件时必须提及文件的绝对路径
res.sendFile(path.join(__dirname, 'Trading Inquiry', 'index.html'));
另一个解决方案我更喜欢
如果提供“/”作为express静态中间件的第一个参数,则将呈现文件名index.html
所以,如果您更改以下行:
app.use('/', express.static(path.join(__dirname, 'Trading Inquiry')));
您不需要index.html的get路由,因此不需要下面的代码
app.get('/', function (req, res) {
console.log(1);
res.sendFile('Trading Inquiry/index.html');
});
当我注释出app.usehistory时,它在我的计算机上工作{index:'Trading Edit:如果我使用app.usehistory而不使用任何索引参数,也可以使用它,但是如果我这样做,根文件夹中的任何其他文件都可以访问?@omega,是的,其他路由也可以。我不明白你为什么要使用'connect history api fallback',它通常用于具有单个index.html的单页应用程序o如果你删除app.usehistory…,所有的路由都会正常工作它需要一个常规的回退,因为如果我使用history api,生成的链接可能类似于/customers/5,虽然fodler结构不存在服务器端,但它是虚拟的。然后如果我将该链接复制到另一个选项卡,你会得到404。这就是为什么服务器端需要一个通用的catch all来返回的原因index.html。
app.get('/', function (req, res) {
console.log(1);
res.sendFile('Trading Inquiry/index.html');
});