How can i render from outside any html documents wit express.router().
My app.js:
const express = require("express");
const fs = require("fs");
const https = require("https");
const path = require("path");
const app = express();
const https_port = 443;
app.use(express.static(path.join(__dirname + '/public')));
const homeRoute = require('./routes/home')
const userRoute = require('./routes/user')
app.use('/user', userRoute)
app.use('/home', homeRoute)
//Create server
https
.createServer(
{
key: fs.readFileSync("ssl/privkey.pem"),
cert: fs.readFileSync("ssl/cert.pem"),
},
app
)
.listen(https_port, () => {
console.log('https server is running on port 443')
});
app.get("/", (req,res) => {
res.sendFile(__dirname + '/index.html');
})
my home.js:
const express = require("express");
const router = express.Router()
router.get("/", (req,res) => {
// res.send("Home site")
res.sendFile(__dirname + '/login.html');
})
router.post("/", (req,res) => {
res.send("Home site")
})
router.put("/", (req,res) => {
res.send("Home site")
})
router.delete("/", (req,res) => {
res.send("Home site")
})
module.exports = router;
The folder structure is:
public
--> index.html
--> login.html
routes
--> home.js
--> user.js
app.js
if i type in the browser http://<MYADRESS>/home
i get this message in browser:
Error: ENOENT: no such file or directory, stat '/root/PWA/routes/login.html
Which is also understandable, because the login.html
file isn´t in the routes folder. But how can i call the login.html
file from my home.js
router file?
i found the redirect()
methode in the Express doc and with ...res.redirect('/login.html');...
it works.
But is this the right way?
app.js
:
const express = require('express');
const fs = require('fs');
const path = require('path');
const homeRoute = require('./routes/home');
const app = express();
app.use(express.static(path.join(__dirname + '/public')));
app.use('/home', homeRoute);
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, './public/index.html'));
});
app.listen(3000, () => {
console.log('https server is running on port 3000');
});
routes/home.js
:
const express = require('express');
const path = require('path');
const router = express.Router();
router.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, '../public/login.html'));
});
module.exports = router;
You can access the index
page via:
Static file: http://localhost:3000/index.html
Route: http://localhost:3000/
Access the login
page via:
http://localhost:3000/login.html
http://localhost:3000/home