So I'm working on developing a Node/Express webapp for basic CRUD operations and I'm having a hard time implementing Handlebars within the project.
When I try to use handlebars none of my stylesheets from my .hbs (previously .html) pages are loading.
Here's the file tree:
Here is the error:
And here is an example of the script import statements from
index.hbs
<!-- Bootstrap -->
<link href="../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
And Finally here is the server.js file
var express = require('express'),
bodyParser = require('body-parser'),
path = require('path'),
mysql = require('mysql'),
dbconfig = require('./config/database'),
exphbs = require('express-handlebars');
var connection = mysql.createConnection(dbconfig.connection)
connection.query('USE ' + dbconfig.database);
var app = express();
//Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//Set static path
//app.use(express.static(path.join(__dirname, 'public')));
//app.use(express.static(__dirname + '/public'));
//app.set('views', __dirname + '/views');
//app.use('/views', express.static(path.join(__dirname, '/views')));
app.engine('hbs', exphbs({defaultLayout: false}));
app.set('view engine', 'hbs');
app.set(express.static(__dirname + '/public'));
//app.use('/views/vendors', express.static(path.join(__dirname, '/views/vendors')));
//app.use(express.static(__dirname + '/public/vendors'));
app.get('/', function(req, res) {
res.render('index');
connection.query("SELECT * FROM Student", function(err, rows){
console.log(rows);
});
});
app.listen(80, function() {
console.log('we are live on 80');
});
I tried using various static paths from other things I found on SO but wasn't able to get any of them to work.
Any help would be greatly appreciated!!
Thanks!
Fixed my problem by adding the following line above my app.get('/'....
app.use("/vendors",express.static(__dirname + "/vendors"));
app.use("/build",express.static(__dirname + "/build"));
app.use("/images",express.static(__dirname + "/images"));
app.get('/', function(req, res) {
I think that can be possible that the problem is in the handlebars configuration, please look at a configuration like this:
app.engine('.hbs',exphbs({
defaultLayout:'layouts',
layoutsDir:path.join(app.get('views'),'layouts'),
partialsDir:path.join(app.get('views'),'partials'),
extname:'.hbs',
helpers: helpers
}));
app.set('view engine','hbs');
maybe in yours it would be:
app.engine('hbs', exphbs({defaultLayout: false, extname:'.hbs',}));
if you are usign app.set(express.static(__dirname + '/public'));
try to put in the public folder your styles for example the bootstrap folder, and then all you have to do is call it in this way:
<link href="/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
Related
Here is my directory
enter image description here
newTab.jade code
doctype html
html
head
title New Tab
link(rel = 'stylesheet', type = 'text/css', href = '/public/index.css')
body
p hello world
index.css code
p{
background-color: black;
color: white;
}
app.js code
const express = require('express');
const app = express();
const port = 3000;
app.locals.pretty = true;
app.listen(port, function(){
console.log("Server Connected port: "+port);
});
app.set('view engine', 'jade');
app.set('views', './views');
app.get('/', function(req, res){
res.render('newTab');
});
jade file can't loading css file.
I tried
href = "/public/index.css"
but it doesn't work too.
Append a middleware to Express to serve static files too.
In your app.js file:
// require path module to join your public folder with __dirname
const path = require('path');
//...
app.get('/', function(req, res){
res.render('newTab');
});
app.use('/', express.static(path.join(__dirname, 'public')));
There are more things express.staticcan do. E.g. setting the maxAge for caching purpose:
// 31557600000ms = 1 year
app.use('/', express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));
suggestion
try
doctype html
html
head
title New Tab
include index.css
body
p hello world
on your newTab.jade file
and include index.css on views directory
Here are some lines of code... I have another application running that is setup exactly the same and I am having no issues.
app.use('/app', express.static(__dirname + "/public"));
Here is the link tag
<link rel="stylesheet" type="text/css" href="/app/css/app.css">
It does the same with this img tag
<img src="/app/img/SCS-NewLogo_donl.svg" height="65px" width="350px" id="sc-logo">
I am not sure why, but it seems to be sending the file as HTML. Usually this means the file is not found on the server, but I checked myself and confirmed that it is.
Full file
const express = require('express');
const config = require('./lib/config');
const bodyParser = require('body-parser');
const URLS = require('./lib/URLS.js');
const PORT = process.env.PORT || 9005;
const ENV = config.ENV || 'TEST';
const SERVER = config.SERVER;
const app = express();
app.set('views', './views');
app.set('view engine', 'ejs');
app.use('/app', express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.all(/^\/apps$/, function (req, res) {
res.redirect('/apps/job-search');
});
app.get('/apps/job-search', (req, res) => {
res.render('pages/search');
});
app.post('/apps/job-search/send-input', (req, res) => {
// Send data to API server which will handle DB query...
axios.get(URLS.GatherSearchResults)
.then(resp => {
console.log(resp.data);
}).catch(err => {
console.log(err)
});
});
app.listen(PORT, () => {
console.log('App is listening on port ' + PORT + ' on server ' + SERVER + '...');
});
Directory Structure
Root
public
css
img
views
pages
search.ejs
partials
header.ejs
footer.ejs
app.js
I thinkk I see your issue. After declaring the route /app as static, you remap it to '/apps/job-search' several lines later.
Change the static line to app.use('/', express.static(__dirname + "/public")); and your links in the HTML file should start wit /css and /img etc.
Verify that by trying to open one of your existing links, and seeing what content you're currently serving (my guess - it'd be whatever is at '/apps/job-search').
I'm trying to render an html page with express. Here's what I have so far:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
app.listen(3000, function() {
console.log('listening on PORT 3000');
})
app.get('/', function(req, res){
res.send('Home page!')
})
app.get('/events', function(req, res){
res.render('eventForm')
})
my file tree so far:
-Project
-node_modules
-public
index.html
-views
eventForm.html
I tried putting the eventForm.html in public as well but for some reason my server can't "find" it. I get the following error:
Error: Failed to lookup view "eventForm" in views directory "/Users/username/LearnProgramming/api_playground/stubhub/views"
set your views before setting view engine
app.set('views', path.join(__dirname, 'views'));
var express = require('express');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.listen(3000, function() {
console.log('listening on PORT 3000');
})
app.get('/', function(req, res){
res.send('Home page!')
})
app.get('/events', function(req, res){
res.render('eventForm')
})
app.use(express.static(__dirname + '/public'));
How about eventForm with .html?
I'm building my first Node application and having some trouble displaying the page that I want with a GET request. I have installed ejs (opinions welcome on that!) so my understanding is that I do not need to define the 'views' folder. Here is my routes file so far:
const express = require('express');
const router = express.Router();
const Event = require('../models/event')
router.get('/'), function(req, res, next){
/* Event.find({}).then(function(events){
res.send(events);
});
});*/
res.render('../../index');
};
router.post('/events', (req, res) => {
Event.create(req.body);
res.send({type: POST})
});
module.exports = router;
The database is connecting just fine, which I can see with the code that I have commented out in the get request. But for some reason I can't render my index file. My file structure is as follows:
File tree:
So I need to go up two levels, correct? I tried index, index.ejs, ../index, views/index, nothing has worked. What am I doing wrong?
EDIT: this is my server.js:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const routes = require('./routes/index');
var path = require("path");
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(routes);
app.use(bodyParser.urlencoded({extended: true}))
mongoose.connect('mongodb://junk:junk#ds141242.mlab.com:41242/alaska-events');
app.listen(3000, () => {
console.log('listening on 3000')
});
views folder is placed directly in root folder, and using we app.set('views', path.join(__dirname, 'views')); point it to views folder. So in render directly mention the view name.
router.get('/', function(req, res, next){
res.render('index');
});
Thanks for your help everyone, turned out to be just a typo. router.get('/'), function(req, res, next) should have been router.get('/', function(req, res, next).
I use an express app to serve an static pre-compiled jade file. which includes a external javascript file. but its not loaded while the page gets loaded. but i can access the javascript by the express static/public url. Why its not loading on the html?
app.js
var express = require('express'),
path = require('path'),
sass = require('node-sass');
var app = express();
/* default configurations */
app.set('views', __dirname + '/public');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'public')));
/* routes */
app.get('/', function(req, res) {
res.send('Hello World');
});
app.get('/home', function(req, res) {
res.render('index.html');
});
module.exports = app;
index.html
<body>
<script type="text/javscript" src="/scripts/site.js"></script>
<script type="text/javascript">
window.onload = function() {
Site.View.init();
}
</script>
</body>
site.js
var Site = Site || {};
Site.View = {
init : function() { alert('view'); }
};
When i open the page in browser i get ReferenceError: Site is not defined
Thanks.
Add app.use('/public/js', express.static(path.join(__dirname, '/public/scripts'))); to app.js, in order to indicate the subfolders of the pulic folder;
If it still not works, change src="/scripts/site.js" to src="/public/scripts/site.js";
site.js must be inside public/scripts from your root directory.
I am not sure but both views and express static pages are gone to public directory in your code.
Use default configuration as:
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
You may also add a route for it like this:
app.get('scripts/site.js', function(req, res){
res.send('./scripts/site.js');
}