我正在使用node和express。我尝试使用express.static创建一个简单的服务器。我的服务器上的以下文件夹中有一个文件:
client/index.html
但是,当我尝试这个网址:http://myServer.com/index.html时,服务器会回答:
Cannot GET /index.html
在这里,您将找到我使用过的代码:
var express = require('express');
var app = express();
app.use(express.static('client'));
/*
app.get('/', function (req, res) {
res.send('Hello World!');
});*/
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
我的文件index.html可用。我已经用其他方式通过使用
来保持这种状态app.get('/index.html', function (req, res, next) {
var options = {
root: __dirname + '/client/',
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
res.sendFile("index.html", options, function (err) {
if (err) {
console.log(err);
res.status(err.status).end();
}
else {
console.log('Sent:', "index.html");
}
});
});
这种方法有效。
答案 0 :(得分:1)
你说你正在尝试这个网址:
http://myServer.com/index.html
但是,您的服务器正在侦听端口8080,因此您需要使用此URL:
http://myServer.com:8080/index.html
或者这个:
由于express.static()
会自动将index.html
用于/
路径。
仅供参考,当我使用正确的URL在我的笔记本电脑上运行您的第一段代码时,它运行正常。浏览器向我显示了client / index.html的内容,其中" client"是下面的一个子目录,我的app.js文件从这里运行以启动服务器。