Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide .html extension in a Node.js server?

I'm using express.js in my Node server.

I have a webpage https://example.com/login.html and i want to be able to access it when typing https://example.com/login.

Since i'm used to Apache and PHP i know how to do it using .htaccess file but in Node.js i have no clue.

like image 233
nadhirxz Avatar asked Jul 25 '18 20:07

nadhirxz


3 Answers

If there are a lot of HTML files, it may be favorable to use express.static instead of creating a route for each file:

app.use(express.static(htmlDir, { extensions: ['html'] }));

where htmlDir points to the directory containing your HTML files. This also works for subdirectories, e.g. /pages serves pages.html but /pages/page1 serves pages/page1.html.

Check out serve-static for additional options such as defaulting to index.html or failing with 404 if no files match.

like image 76
Lucas S. Avatar answered Oct 01 '22 20:10

Lucas S.


var express = require('express');
var app = express();
app.set('port', (5000));
app.get('/login', function(req, res) {
    res.render('login'); // no need to use '.html'
});
like image 33
jatinder bhola Avatar answered Oct 01 '22 20:10

jatinder bhola


It's simple.

Put this at the top of your code

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

And add this to your code

app.get('/login', function(req, res) {
    res.sendFile(__dirname + '/public/login.html'); // replace /public with your directory
});
like image 25
Cryptic Avatar answered Oct 01 '22 21:10

Cryptic