derek derek - 3 months ago 39
Node.js Question

nodejs/expressjs redirect does not work

I tried to serve a webpage with redirect function in expressjs. But it somehow cannot work. I must be dumb on something here.

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);


Both files are in the same directory. I can see the log "reached log" on browser console but I got a 404 error: "Cannot GET /index.html".
However, if I redirect to a outside webpage, it can work. If I change "res.redirect("index.html");" to "res.redirect("http://google.com");", it can work perfectly.

Answer

node.js does not serve any files by default. So, it doens't matter what files on on your hard disk. If there's no route to serve those files, Express will never send them.

So, if you're going to redirect to /index.html, then you need a route to serve that request. As your server is now, that request is going to generate a 404 (route/file not found).

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);

Perhaps what you want to do is to just render 'index.html' without a redirect. That could work with the one route you have.

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

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

These examples assume the file index.html is in the app directory. If it is located elsewhere, then you need to adjust the path for sendFile() appropriately.

For static files, you can also use express.static() to automatically serve a whole directory of files. See the express.static() doc for details.