My css style it's not showing up, nodejs, express, hbs - node.js

I've made this sample code, but first let me show you my folder struture.
---public
-----css
------style.css
---views
-----video.hbs
-----video2.hbs
---server.js
this is my server code.
const express = require('express');
const app = express();
const hbs = require('hbs');
const port = process.env.PORT || 8080;
app.use(express.static(__dirname + '/public'))
//Express hbs engine
hbs.registerPartials(__dirname + '/views/parciales');
app.set('view engine', 'hbs');
app.get('/video', (req, res) => {
res.render('video.hbs');
});
app.get('/video/2', (req, res) => {
res.render('video2.hbs');
});
app.listen(port, () => {})
Now the problem is the next... When I got to localhost:8080/video my css is working fine but when I goin to /video/2 my css it's not showing up, any solution?

You're probably importing your CSS as ./css/style.css. You need to import it as /css/style.css.

Related

Express not interpreting URL path correctly for static files

I am building a Node.JS app with Express and Handlebars to serve the public content. The app is running in pm2.
The app is working fine, but I want to serve static files. I added 2 static routes which are loaded fine when I check the Express log.
But when I try to access the files, I get a 404. I noticed the message on the 404 states "Cannot GET /js" where I would expect "Cannot GET /scripts/scripts.min.js".
The URL should be on /scripts/scripts.min.js, internally it's located inside a public folder:
app.js
public
scripts
scripts.min.js
images
styles
Here is my app.js:
const express = require('express');
const { engine } = require('express-handlebars');
require('dotenv').config();
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const {
NODE_ENV,
PORT,
HOST,
} = process.env;
// Use body-parser middleware
app.use(bodyParser.json());
// Use express-handlebars as the view engine
app.engine('handlebars', engine({
defaultLayout: 'main',
layoutsDir: __dirname + '/views/layouts',
partialsDir: __dirname + '/views/partials',
}));
app.set('view engine', 'handlebars');
app.set('views', __dirname + '/views');
app.use(express.static(path.join(__dirname, 'public')))
app.use('/scripts/monaco/', express.static(path.join(__dirname, 'node_modules','monaco-editor','min','vs')));
// Define routes
app.get('/', (req, res) => {
res.render('home', { title: 'Home' });
});
app.get('/debug', (req, res) => {
res.send(__dirname + '/public')
})
app.post('/', (req, res) => {
console.log(req.body);
res.send('Success');
});
// Load external routes (also tried the staticFiles by using res.sendFile)
require('./routes/processing')(app);
// require('./routes/staticFiles')(app);
// Start the server
app.listen(PORT, () => {
app.currentServer = {
host: HOST ? HOST : "127.0.0.1",
port: PORT,
};
console.log(`Server init on: http://:${PORT}`);
});
I tried serving the files using express.static, I also tried sending them trough specific routes by using res.sendFile.
It looks like Express (or something else) is interpreting the URL path incorrectly. /scripts/scripts.min.js is downgraded to /js so it seems.
I hope anybody has a clue!

exphbs is not a function

I have been trying to test out express and express handlebars. I have read and tried a few demos. They all basically the same but I cannot get any of them to work. The error I keep getting is -
app.engine('handlebars', exphbs());
^
TypeError: exphbs is not a function
here is my code below:
const express = require("express");
const exphbs = require("express-handlebars");
const app = express();
const port = 8000;
//Handelbars Middleware
app.engine("handlebars", exphbs());
app.set("view engine", "handlebars");
// Index Route
app.get("/", function (req, res) {
res.render("home");
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
I made a short video to further explain - https://www.awesomescreenshot.com/video/6352907?key=df18cdbdf4ed12b85d2c92458ad9a2de
I thought const exphbs = require('express-handlebars'); was declared a function
Thanks
exphbs is not function u can try this code..
const express = require('express');
const exphbs = require('express-handlebars');
// const { engine } = require('express-handlebars');
const app = express();
const port = 8000;
//Handelbars Middleware
//app.engine('handlebars', engine());
app.engine('handlebars', exphbs.engine());
app.set('view engine', 'handlebars');
// Index Route
app.get('/', function (req, res) {
res.render('home');
});
app.listen(port, () =>{
console.log(`Server started on port ${port}`);
});
I think You should use example as reference from express-handlebars. To use this code you need add to your pacakge.json file this line "type": "module",(ES6 import) Good Luck!
import express from 'express';
import { engine } from 'express-handlebars';
const app = express();
app.engine('handlebars', engine());
app.set('view engine', 'handlebars');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('home');
});
app.listen(8000);

Express app: Error: Failed to lookup view "index" in views directory "views"

I am working along with a tutorial to learn MVC and I am unable to get my views to render. When I try to render my views locally I receive the following error. I'm not well versed in serving views from express, so I'm not sure about what steps to take in trouble shooting this error.
Error: Failed to lookup view "index" in views directory "views"
My app.js file reads as follows:
const path = require("path")
const express = require('express');
const app = express()
const port = process.env.port || 3000
// express middelware
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(express.static("public"))
// views are the files you render
app.set("views", "views")
app.set("view engine", "hbs")
// end express middleware
app.get("/", (req, res) => {
res.render("index")
})
app.get("/about", (req, res) => {
res.render("about")
})
app.listen(port, () => {
console.log(`listening on port ${port}`)
})
My file setup is as follows:
const path = require("path")
const express = require('express');
const app = express()
const port = process.env.port || 3000
// express middelware
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(express.static("public"))
// views are the files you render
app.set('views', __dirname + '/../views');
app.set("view engine", "hbs")
// end express middleware
app.get("/", (req, res) => {
res.render("index")
})
app.get("/about", (req, res) => {
res.render("about")
})
app.listen(port, () => {
console.log(`listening on port ${port}`)
})
You need to reference the views folder as part of the directory path.
app.set('views', __dirname + '/../views');

routing problem in express.js with html and hbs view engine

router.get('/dist/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
my app.js routing code
app.set('dist', path.join(__dirname, 'dist'));
app.set('view engine', 'html');
app.engine('html', require('hbs').__express);
my folder structure
root/dist/index.html
I cannot open this page on my first page
how can I open this page? Where is my mistake?
thank you for your help
You can use the method set() to redefine express's default settings.
app.set('views', path.join(__dirname, '/dist'));
Working Example
const express = require('express')
const path = require('path')
const app = express()
const port = 3000;
var indexRouter = require('./routes/index');
// Set 'views' directory for any views
// being rendered res.render()
app.set('views', path.join(__dirname, '/dist'));
// Set view engine
app.engine('html', require('hbs').__express);
app.set('view engine', 'html');
app.use('/', indexRouter);
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/dist/', function(req, res, next) {
res.render('index', { title: 'Inside Dist Folder Index' });
});
module.exports = router;

Cant get ejs page to render

I want to get my news.ejs page to render when i click its link, but i get a error called "Cannot GET /news.ejs"
const express = require('express')
const path = require('path')
const PORT = process.env.PORT || 5000
express()
.use(express.static(path.join(__dirname, 'public')))
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'ejs')
.get('/', (req, res) => res.render('pages/index'))
.get('/news', (req, res) => res.render('pages/news'))
.listen(PORT, () => console.log(`Listening on ${ PORT }`))
I have this code and working fine
const express = require('express');
const app = express()
const path = require('path')
const ejs = require('ejs');
app.use(express.static(path.join(__dirname, 'public')))
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', ejs)
app.get('/', (req, res) => res.render('privacypolicy.ejs'))
app.get('/news', (req, res) => res.render('rulesnregulations.ejs'))
//app.use('/', indexRouter)
const PORT = 5000;
app.listen(PORT, () => console.log('it started on 5000'))
privacypolicy.ejs & rulesnregulations.ejs these two files are under views folder
Make sure you are linking to /news and not /news.ejs. If you want /news.ejs to be accessible, you will have to change the path that you are registering.

Resources