Not link css file with ejs - css

I am working with simple express node js But my main.css file does not link with header.ejs both are the same folder shown in below picture.
I have searched on google but the problem still there.
my app.js file code
var express = require("express")
var app = express()
var request = require("request");
app.set("view engine", "ejs");
app.get("/", function(req, res){
res.render("search");
});
app.get("/results", function(req, res){
var url ="http://www.omdbapi.com/?s="+req.query.search+"&apikey=my_api_key"
request(url, function(error, response, body){
if(!error && response.statusCode == 200){
var data = JSON.parse(body)
// res.send(results["Search"]);
res.render("results",{data: data});
}
})
});
app.listen(5000,"localhost",function(){
console.log("movie search");
})

You have a wrong setup, Your view folder should only contain view files (in your case *.ejs files) but not static content.
Create another folder with name 'public' at root of your node project and move your main.css there and add the following code to serve static content.
app.use(express.static(__dirname + '/public'));
After this you should be able to access your main.css using localhost:5000/main.css If you see your content, The css import in your view file will start working.

Related

Alerts in bootstrap & pug

I would like to know whether i have understood the workings of connect-flash/bootstrap/sessions. I do see the flash messages appear as expected. My question is to do with the colors related to the 'success' and 'danger'. While the messages appear as expected i am not seeing the associated colors,
Below are bits of package.json,
{
"dependencies": {
"body-parser": "^1.18.3",
"bootstrap": "^4.1.3",
"connect-flash": "^0.1.1",
"cookie-parser": "^1.4.3",
"express": "^4.16.4",
"express-messages": "^1.0.1",
"express-session": "^1.15.6",
"express-validator": "^5.3.0",
"mongoose": "^5.3.15",
"pug": "^2.0.3"
},
"devDependencies": {
"nodemon": "^1.18.7"
}
}
In my app.js,
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
// express session middleware
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}));
// express messages middleware
app.use(require('connect-flash')());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use(flash());
// my routes
let quotes = require('./routes/quotes');
let subscribers = require('./routes/subscribers');
app.use('/quotes', quotes);
app.use('/subscribers', subscribers);
// In my subscribers route,
router.post('/subscribe', function (req, res)
{
// logic to save to my database here
req.flash('success', 'Subscription confirmed.');
res.redirect('back');
});
In my services.pug file i have,
link(rel='stylesheet', href='/css/style.css')
link(rel='stylesheet' href='/node_modules/bootstrap/dist/css/bootstrap.css')
// other code in here
.container
h1 Subscribe to our newsletter
//- include subscribe.pug
form(method='POST', action= '/subscribe')
input(name = 'email',type='email', placeholder='Enter email')
button.button1(type='submit') Subscribe
!= messages('message',locals)
// at the bottom
script(src='/node_modules/jquery/dist/jquery.js')
script(src='/node_modules/bootstrap/dist/js/bootstrap.js')
In my message.pug i have,
.messages
each type in Object.keys(messages)
each message in messages[type]
div(class = "alert alert-"+ type) #{message}
Like i mentioned above the messages appear as expected. But i do not see the green color associated with success and the red for danger as i have seen in a tutorial i followed. I just see the message blended with the background color of the page. I would like to know what i am missing.
UPDATE
On checking the console on chrome i found the attached error messages. I have included the directory structure of the project as well. The bootstrap.css and jquery.js are not being found by the app.
This is where i set my public folder in app.js,
// set public folder
app.use(express.static(path.join(__dirname, 'public')));
The node_modules folder is available as well.
Thank you
You also need to serve bootstrap and jquery dist folders beside the public one:
// set public folder
app.use(express.static(path.join(__dirname, 'public')));
// serve bootstrap and jquery
app.use(express.static(path.join(__dirname, 'node_modules', 'bootstrap', 'dist')));
app.use(express.static(path.join(__dirname, 'node_modules', 'jquery', 'dist')));
and use them ( make sure styles are in head tag ):
link(rel='stylesheet' href='/css/bootstrap.css')
link(rel='stylesheet' href='/css/style.css')
and:
script(src='jquery.js')
script(src='/js/bootstrap.js')
of course in production you should use minified versions ( i.e: bootstrap.min.js ) or simply a CDN ( or both: when CDN is not available fall back to local ones )

Can't load CSS file (error in console log) on "localhost:3000/" in node.js?

re]5]5app.js file:
const express = require('express'),
app = express();
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'jade');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('index')
});
app.listen(3000);
console.log('listening on port 3000');
index.jade file:
doctype
html
head
title Home
link(rel='stylesheet', href='css/style.css')
body
header
h1 Home
footer
p Designed By Me
When I load the browser at localhost:3000/, I get 404, failed to load "localhost:3000/css/style.css". Whats the problem???
directory structure:
root
public
css
style.css
app.js
views
index.jade
THNX

Static files with Express

I am trying to link a stylesheet in a jade template, and am getting a 404. I have the exact path to the stylesheet, and have my app configured to serve up static files from my 'static' directory, but I am still getting a 404 ? Also why do static files need to be served up ? Why can't they just be linked to in your templates ?
'use strict';
var express = require('express');
var app = express();
app.set('view engine', 'jade')
app.set('views', __dirname + '/templates')
app.listen('3000', function(){
console.log('Running on port 3000');
})
app.use(express.static(__dirname + '/static'));
// Routes
app.get('/', function(request, response){
response.render('index')
});
app.get('/blog:id', function(request, response){
response.send('This is the blog page.')
})
app.get('/about', function(request, response){
response.send('This is the about page.')
})
Jade template
html
head
link(rel="stylesheet", href="../../static/css/normalize.css")
link(rel="stylesheet", href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css", integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7", crossorigin="anonymous")
link(rel="stylesheet", href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css", integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r", crossorigin="anonymous")
body
div.hero(style="width: 100%; height: 400px; background-color: blue")
h1(style="color: white;") This is the landing page !
script(src="https://code.jquery.com/jquery-2.2.3.min.js", integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=", crossorigin="anonymous")
script(src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js", integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS", crossorigin="anonymous")
You can have your css file url relative to the static folder
link(rel="stylesheet", href="/css/normalize.css")

How to specify the location of kml file when using geoxml3 parser with meteor js

I have been trying to parse a kml file using the geoxml3 parser. The geoxml3.js file is put in the public folder. The parser is working fine if I put the kml file inside the public folder.
geoXml.parse('doc.kml'); // this is working fine
But how can I make it work if the kml file is located somewhere else, say in the 'uploads' folder outside the public folder. I have tried,
geoXml.parse(uploadPath+'/doc.kml');
but this is not working. How should I specify the file path ? I can't put the kml files in the public folder as any change inside the folder will make the page refresh.
Please help me out.
Haven't tried this one, but Assets.getText() may be what you're looking for. The documentation
specifies that you pass it a file path relative to your private directory.
Well, could not resolve the path issue. Assets.getText() is dependent on the private folder and also it doesn't stop the server from restart. But found an alternative solution, where you can upload the file to any folder within your project app and read from it.
// On client side
Meteor.call('getKmlString', kml_file_name, function(error, kml_string) {
if (error) {
console.log('ERROR in getting kml string');
console.log(error);
} else {
console.log('GOT Kml String');
geoXml.parseKmlString(kml_string);
}
});
// On server side
Meteor.startup(function() {
// code to run on server at startup
return Meteor.methods({
getKmlString: function(kml_file_name) {
var content = '';
var fs = Npm.require('fs');
var encoding = encoding || 'binary';
var chroot = Meteor.chroot || 'uploads';
var path = chroot + (path ? '/' + path + '/' : '/');
var content = fs.readFileSync('../../../../../' + path + kml_file_name, "utf-8", function read(err, data) {
if (err) {
throw err;
}
});
return content;
},
});
});

Why is my node static file server dropping requests?

I have a standard node.js static file server that I want to use to serve normal html, js, css, and jpg files in the same directory (ie- a typical HTML5 single page app). I would expect that the node server can handle this properly. What I see is different.
The index.html file is served, but then subsequent requests are dropped (ie- they never make it to the server). In my chrome dev tools, I see things like this:
GET http://projectcoho.cloudfoundry.com/css/coho.css http://projectcoho.cloudfoundry.com/:7
GET http://projectcoho.cloudfoundry.com/sencha-touch/sencha-touch-debug.js http://projectcoho.cloudfoundry.com/:8
GET http://projectcoho.cloudfoundry.com/coho-debug.js http://projectcoho.cloudfoundry.com/:8
But, these resources exist on the server and you can reach them if you enter their URL directly. And for these requests, my callback in app.js is never invoked (I can tell this because console.log is never called for these files.
Here is the app.js file:
var path = ".";
var port = process.env.VCAP_APP_PORT || 3000;;
var file = new(static.Server) (path, {
cache: 600
});
mime.define({
'text/css': ['css'],
'text/javascript': ['js'],
'image/jpeg': ['jpg', 'jpeg']
});
http.createServer(function (request, response) {
var uri = url.parse(request.url).pathname;
var filename = libpath.join(path, uri);
console.log("URI: " + request.url + " , filename: " + filename);
libpath.exists(filename, function (exists) {
console.log("Serving " + filename);
if (!exists) {
console.log("Not found");
response.writeHead(404, {
"Content-Type": "text/plain"
});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) {
filename += '/index.html';
}
var type = mime.lookup(filename);
file.serveFile(filename, 200, {'content-type' : type}, request, response);
});
}).listen(port);
What am I missing here?
I am using node v0.6.15
In the end, the answer was that my cache.manifest file was incorrect. The client application was looking for resources in a cache, but the didn't exist. When I corrected the manifest, things started working.

Resources