Hey guys so I have the following in my app.js file
const express = require("express");
const app = express();
const path = require('path');
const hbs = require("express-handlebars");
app.engine(
"hbs",
hbs({
extname: "hbs",
//defaultLayout: "layout",
layoutsDir: __dirname + "/views/layouts/"
})
);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "hbs");
I also have a file located in server/views/layouts/ that is a handle bars file called share.hbs
I also have a file in my server/api/media.js that looks like this
const express = require("express");
const router = express.Router();
const database = require("../db");
router.get("/share", async (req, res, next) => {
res.render("share");
});
But when ever I try to render the file it errors out with the following error
Had to move my file out of the layouts folder and add this to the res.render call
res.render("share.hbs", { layout: "share" });
Related
Here is my express code:
const express = require('express');
const serveStatic = require('serve-static');
const path = require('path');
// create the express app
const app = express();
var cors = require('cors');
app.use(cors());
app.use("/",serveStatic ( path.join (__dirname, '/dist') ) );
app.use('/static', express.static(path.join(__dirname, '/dist23')));
app.listen(port, () => {
console.log("listening on "+port)
});
The above code only works for the folder /dist. But when I go to /static, it shows a blank page and this error in the console:
If I put the js files from /dist23 into /dist, then /static works and shows me the application. Its almost like it is looking for files inside /dist and not /dist23. How do I fix it?
Both apps were built using vue-2.6.11. Both directories have files built/bundled for production.
You need to set the content type while serving your static files.
app.get('/index.html', (req, res) => {
res.set('content-type', 'text/plain').sendFile('index.html', { root: path.join(__dirname, 'public/dist/') })
});
app.get('/', (req, res) => {
res.set('content-type', 'text/plain').sendFile('index.html', { root: path.join(__dirname, 'public/dist/') })
});
Hope Youre all are doing Great,Im new in Expressjs and doing a project in it.
Actually I m getting problem to render a file that is place inside the a folder named as index.hbs in views directory,
When I try to access a found this error :
Error: Failed to lookup view "/blogger_dasboard" in views directory "C:\Users\HBK1007\Desktop\ExpressjsFyPEPakTourisum\template\views"
Im attaching folder structure images and my code as well
Here is the codeenter image description here
`
const express = require("express")
const app = express()
const path = require('path')
const port = 8000;
const hbs =require('hbs')
const bcrypt =require("bcryptjs")
// establishing db connection
require('./db/db_connec');
// Getting the collection of DB
const Registration=require('./models/registrationdb')
const NewsletterSubsciber=require('./models/newsletter')
const ContactUs_Client =require("./models/contactus")
// this is for DB data conersions
app.use(express.json());
app.use(express.urlencoded({extended:false}))
//public static port
const static_path = path.join(__dirname, '../public')
const tempalte_path = path.join(__dirname, '../template/views')
const bloggerdashboard_path = path.join(__dirname, '../template/views/blogger_dashboard')
const partials_path =path.join(__dirname,'../template/particles')
app.set('view engine', 'hbs');
app.set('views', tempalte_path)
hbs.registerPartials(partials_path)
app.use(express.static(static_path))
// BloggerDashboard Routes
app.get('/blogger_dashboard', (req, res) => {
res.render('/blogger_dasboard')
})
app.listen(port, () => {
console.log("Listning to portss ")
})
I mirrored your project and You have few errors:
Wrong paths, too many by one dot in : static_path, tempalte_path, bloggerdashboard_path, partials_path.
Insted of res.render("/blogger_dasboard") like that: res.render("blogger_dashboard"); Without slash and you missed h letter.
Working example below without static_path bcrypt and db (for obvious reasons)..
const express = require("express");
const app = express();
const path = require("path");
const port = 8000;
const hbs = require("hbs");
// const bcrypt = require("bcryptjs");
// establishing db connection
// require("./db/db_connec");
// Getting the collection of DB
// const Registration = require("./models/registrationdb");
// const NewsletterSubsciber = require("./models/newsletter");
// const ContactUs_Client = require("./models/contactus");
// this is for DB data conersions
// app.use(express.json());
app.use(express.urlencoded({ extended: false }));
//public static port
// const static_path = path.join(__dirname, "./public");
const tempalte_path = path.join(__dirname, "./template/views");
const bloggerdashboard_path = path.join(
__dirname,
"./template/views/blogger_dashboard.hbs"
);
const partials_path = path.join(__dirname, "./template/particles");
app.set("view engine", "hbs");
app.set("views", tempalte_path);
hbs.registerPartials(partials_path);
// app.use(express.static(static_path));
// BloggerDashboard Routes
app.get("/blogger_dashboard", (req, res) => {
res.render("blogger_dashboard");
});
app.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`);
});
My Project folder and file structure:
I have read through posts about this issue but I just can't figure out what I am doing wrong.
What I would like is to separate each of my route (login and register for now) into their own separate file, reference those files in routes/user/index, then use that in server.js. This is what I have now:
server.js
ROUTES
USER
index.js
LOGIN
index.js
REGISTER
index.js
server.js
const express = require("express");
const app = express();
(...)
app.use("/user", require("./routes/user"));
(...)
routes/user/index.js
const express = require("express");
const router = express.Router();
router.use("/login", require("./login"));
router.use("/register", require("./register"));
module.exports = router;
routes/user/login/index.js
const express = require("express");
const router = express.Router();
router.post("/login", async (request, response) => {
(...)
});
module.exports = router;
routes/user/register/index.js
const express = require("express");
const router = express.Router();
router.post("/register", async (request, response) => {
(...)
});
module.exports = router;
All I get is a 404 error. Any help would be appreciated.
Thanks!
You can create chainable route handlers for a route path by using app.route()
const express = require("express");
const router = express.Router();
router.route("/login").post((request, response) => {
//Your code goes here
});
module.exports = router;
OK, after a few more hours of googling & trial/error I finally figured it out. For some reason I didn't find earlier this setup guide but it was pretty much what I wanted.
I'm using express.js and ejs.
I will post below two codes for the app.js file. The thing is that ejs and layout.ejs do not work with the one of those two codes, but it works perfectly with the other
Here are the two codes:
The first one, which ejs is working:
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const path = require('path')
const app = express();
// Bodyparser
app.use(express.urlencoded({extended:false}));
/// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
//PUBLIC FOLDER(css and js)
app.use(express.static(path.join(__dirname,'/public')));
// Express body parser
app.use(express.urlencoded({ extended: true }));
// Routes
app.use('/', require('./routes/index.js'));
app.use('/users', require('./routes/users.js'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server started on port ${PORT}`));
and the second one, which ejs is not working:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 5000;
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const path = require('path')
// Bodyparser
app.use(express.urlencoded({extended:false}));
//ROUTES
app.use('/', require('./routes/index'))
app.use('/users', require('./routes/users'))
// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
app.set('view options', { layout:'layout.ejs' });
//PUBLIC FOLDER(css and js)
app.use(express.static(path.join(__dirname,'/public')));
//DB CONFIG
const db = require('./config/keys').MongoURI;
// //Connect to mongo
mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then( () => console.log('MongoDB Connected...'))
.catch( err => console.log(err));
app.listen(PORT, console.log(`Server started on PORT ${PORT}`));
I'm trying to figure out what's the issue with the second code and doesn't make the ejs work. Can anyone have a quick glimpse and compare these two and tell me what's the problem? Thank you for your time
Can someone help me why default route is not working in my Mean App, But the next routing works
Here when I open http://localhost:3000 I am not able to see any output, But I have defined route in route.js which is working
var express = require('express');
var cors = require('cors');
var bodyparser = require('body-parser');
var mongoose = require('mongoose');
var path = require('path');
const port = 3000;
app.get('/', function (req, res) {
res.send('Test');
console.log('Opened the root path');
});
When I open the page with http://localhost:3000/main I am able to see the Output and also log written in the console
const express = require('express');
const router = express.Router();
router.get('/main', function (req, res, next) {
res.send('This is the Admin Landing Page');
});
router.get('/install', function (req, res, next) {
res.send('This is the Install Landing Page');
console.log('Opened the Install path');
});
module.exports = router;
It looks like you the code you pasted is the full version, and it's not runnable because:
You did not declare app variable.
You did not start the http server.
It's really hard to tell the root cause what's wrong of your code. Following codes works for me:
const express = require('express');
const port = 3000;
let app = express();
app.get('/', function (req, res) {
res.send('Test');
console.log('Opened the root path');
});
let server = require('http').createServer(app);
server.listen(port, function() {
console.log('Server started');
});