Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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?

like image 258
user3552178 Avatar asked Nov 20 '15 02:11

user3552178


2 Answers

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/') });
like image 156
Ryan Jenkin Avatar answered Oct 18 '22 00:10

Ryan Jenkin


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" )
    )
})
like image 30
Devmaleeq Avatar answered Oct 17 '22 23:10

Devmaleeq