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.
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.
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'
});
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With