- File structure:
- Commands:
- npm init OR npm init -y
- npm i
- npm i express hbs
- Run command - node app.js OR nodemon app.js
- Other:
- index.html -> index.hbs
- {{<headLinks}}
- Create server from node.js:
const { createServer } = require('node:http');
const hostname = '127.0.0.1';
const port = 8000;
const server = createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
- Create server from express.js:
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000);
// if user search your other pages
app.get("*", (req, res) =>{
res.render("404Error", {
errorMsg: "Opps! Page Not Found"
});
});
- Add static path to access the css, script, img:
// Static path
app.use(express.static(path.join(__dirname, '/public')));
- By default, Express looks for views in a folder named views in the root directory of your project.
- But we created views folder in the templates folder. So we need to set the path from views to templates folder.
// Set up view engine
app.set('view engine', 'hbs');
// Set up path for views engine
app.set('views', path.join(__dirname, '/public/templates/views'));
// hbs can access the components(reuseable) which is respresent in the partials folder
hbs.registerPartials(path.join(__dirname, '/public/templates/partials'));
0 Comments