nodejs / expressjs重定向不起作用

时间:2016-08-13 17:13:00

标签: node.js redirect express

我尝试在expressjs中提供具有重定向功能的网页。但它在某种程度上无法奏效。我必须对这里的事情愚蠢。

的index.html:

<html>

<body>
    <div id="clicked"> not clicked </div>
</body>

</html>

server.js:

var express = require("express");
var app     = express();

app.get('/', function(req, res) {
    console.log("reached root!");
    res.redirect("index.html");
});
app.listen(9876);

两个文件都在同一目录中。我可以在浏览器控制台上看到日志“到达日志”,但我收到了404错误:“无法获取/index.html”。 但是,如果我重定向到外部网页,它可以工作。如果我更改“res.redirect(”index.html“);” to“res.redirect(”http://google.com“);”,它可以很好地工作。

2 个答案:

答案 0 :(得分:2)

node.js默认不提供任何文件。因此,硬盘上的文件无关紧要。如果没有提供这些文件的路由,Express将永远不会发送它们。

因此,如果您要重定向到/index.html,那么您需要一条路线来提供该请求。正如您的服务器现在,该请求将生成404(未找到路由/文件)。

var express = require("express");
var app     = express();

app.get('/', function(req, res) {
    console.log("reached root!");
    res.redirect("/index.html");
});
app.get('/index.html', function(req, res) {
    console.log("reached root!");
    res.sendFile("index.html");
});
app.listen(9876);

也许你想做的就是在没有重定向的情况下渲染'index.html'。这可能适用于您拥有的一条路线。

var express = require("express");
var app     = express();

app.get('/', function(req, res) {
    console.log("reached root!");
    res.sendFile("index.html");
});
app.listen(9876);

这些示例假设文件index.html位于app目录中。如果它位于其他位置,则需要适当调整sendFile()的路径。

对于静态文件,您还可以使用express.static()自动提供整个文件目录。有关详细信息,请参阅express.static() doc

答案 1 :(得分:0)

我不确定,但我想您可能想使用res.sendFile而不是重定向到另一个网址。查看api了解详细信息: http://expressjs.com/en/api.html