user3552178
user3552178

Reputation: 3003

Node.js: how to make default page to be sth. other than index.html

Originally, my node.js server goes to index.html by default. Now I want to default to login.html so people can log in first.

My code is in .../server/server.js, while client page are in .../client/login.html, index.html, etc.

Now I modified server.js to be like this:

app.get('/', function(req, res)
{
    res.sendfile(path.resolve('../client/login.html'));
});

After restart server.js, the webpage is still pointing to index.html by default. What am I missing?

Upvotes: 8

Views: 11851

Answers (2)

Devmaleeq
Devmaleeq

Reputation: 586

If you also have a router that's handling getting an index page for you and you want to render a handlebar page or do something else instead, you can put anything in the index option and it will ignore it if not found in your static asset folder:

app.use(
    express.static(
        path.resolve(__dirname, "../Client/assets/"),
        {index: "userouterinstead"}
    )
)

app.use("/", route_configs)

app.get("*",  (req, res, next) => {
    res.sendFile(
        path.resolve( __dirname, "../Client/assets/index.html" )
    )
})

Upvotes: 1

Ryan Jenkin
Ryan Jenkin

Reputation: 924

If you're running ExpressJS on top of Nodejs, you can serve the files statically using the static method. The first parameter is the directory and the second allows you to specify the default file.

app.use(express.static('../client/', {index: 'login.html'}))

http://expressjs.com/guide/using-middleware.html#middleware.built-in

For your specific example, you can modify the sendFile to include the root with the second parameter:

res.status(200).sendFile('login.html', { root: path.join(__dirname, '../client/') });

Upvotes: 10

Related Questions