why my css not finding? - node.js

I have attached my css file to my html file. And then i run and open page using express in node js. However, the css file does not open when i run the webserver through node js.
html(show.ejs)
<html>
<head>
<link rel="stylesheet" type="text/css" href="assets/css/style.css" media="screen" />
</head>
<body>
<h1> Value is <%= detail %></h1>
</body>
</html>
node js
//required npm
var express = require('express');//express 4.*
var path = require('path');
// define app
var app = express();
// set up template engine
app.set('view engine', 'ejs');
//static files
//app.use('/static', express.static('/public')); //not working
app.use('', express.static(path.join(__dirname, 'public'))); //not working
//app.use(express.static(__dirname + '/public')); //not working
//app.use('/public/assets', express.static('public/assets')); //not working
app.get('/show/:id', function (req, res) {
res.render('./panel/show', {
detail: req.params.id ,
});
//port
app.listen(3000);
my project folder
node_modules
views
panel
show.ejs
public
assets
css
style.css
app.js
package.json

By entering <link rel="stylesheet" type="text/css" href="assets/css/style.css" media="screen" /> You are trying to find the assets folder in your out of public directory.
So, when you / it will find public directory which is statically defined in express server.
<html>
<head>
<link type="text/css" href="/assets/css/styles.css" rel="stylesheet">
</head>
<body>
<h1> Value is <%= detail %></h1>
</body>
</html>

Related

Express js app.use() not working properly?

Alright guys, I've been following the fcc node js tutorial for beginners. I have trouble getting the use() function from the express framework to work. I followed all the steps (I've copied exactly what he's doing), but when I open the Chrome/Firefox debug console my I can see my folders are not swapped for the alias I've set (is 'static' instead of 'public'). For anyone wondering, I'm stuck on this part -> https://youtu.be/-FV-moMWRSA?t=230.
my code:
const path = require('path');
const express = require('express');
const app = express(); //this function returns an object with many functions
app.use('/public', express.static(path.join(__dirname, 'static')));
app.get('/',
(req, res) => {
res.sendFile(path.join(__dirname, 'static', 'index.html'));
});
app.listen(3000);
my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="/static/css/main.css">
<script src="/static/js/main.js"></script>
</head>
<body>
<p>Test paragraph</p>
</body>
</html>
anyone know what's going on?
You have wrong paths in your html. Since you're using /public in your middleware, only requests with /public will be looked in the static folder to see if a filewith the requested name exists or not.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="/public/css/main.css">
<script src="/public/js/main.js"></script>
</head>
<body>
<p>Test paragraph</p>
</body>
</html>
Hope this helps !

Can node presented ejs files use offline bootstrap?

I'm new to node and full stack development and hope I ask this correctly and not carelessly or offensively for your particular level of understanding.
My dev environment is Internet connected, production will not be and I want to use bootstrap.css with node. Apache/httpd is not an option in production.
Testing bootstrap locally has been challenging, the correct directory for the css file is believed correct.
The main directory on CENTOS 7 is myapp, contains app0.js, the node_modules with espress and body-parser and all dependencies, and the views directory which contains grid.ejs.
myapp/
app0.js
node_modules
views/
grid.ejs
public/
bootstrap.css
Here is grid.html (which works on apache):
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Grid Test</title>
<link rel="stylesheet" type="text/css" href="bootstrap.css">
<style type="text/css">
.pink {
background: yellow;
border: 3px solid red;
</style>
</head>
<body>
<div class="row">
<div class="col-lg-2 pink"><center>2 columns </center></div>
<div class="col-lg-7 pink"><center>7 columns </center></div>
<div class="col-lg-3 pink"><center>3 columns </center></div>
</div>
</body>
</html>
And here is what apache shows for grid.html:
https://imgur.com/VanVZJn "bootstrap with httpd"
However app0.js does not!
So bootstrap.css works (1) when referenced on internet - which I cannot use in production (2) from httpd in my dev environment via http code
but not from an ejs file.
Note: I am able to reach bootstrap from node, because there were 404 errors when it was not reachable showing from the terminal where node was launched. After at least 12 hours trying to understand this, I'm stumped. Sadly with a short timeline to have a solution, I turn to you fine readers!
App0.js
//setup
var express = require('express'),
app = express(),
bodyParser = require('body-parser')
app.set('view engine','ejs');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.get("/grid", function(req, res, next){
res.render("grid")
});
app.listen(3000,function(){
console.log("serving test demo on port 3000")
});
views/grid.ejs
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Grid System</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="public/bootstrap.css">
<style type="text/css">
.pink {
background: yellow;
border: 3px solid red;
}
</style>
</head>
<body>
<div class="row">
<div class="col-lg-2 pink"><center>2</center></div>
<div class="col-lg-7 pink"><center>7</center></div>
<div class="col-lg-7 pink"><center>3</center></div>
</div>
</body>
</html>
shown here:
https://imgur.com/ZLOgZKT "bootstrap not working"
You have to define on your app0.js file the public path from where you are going to serve static files. Try the following app0.js file requiring the path module and using express.static after bodyParser.json():
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
path = require('path')
app.set('view engine','ejs');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, 'public')));
app.get("/grid", function(req, res, next){
res.render("grid")
});
app.listen(3000,function(){
console.log("serving test demo on port 3000")
});
And your grid.ejs file link the bootstrap file this way:
<link rel="stylesheet" type="text/css" href="/bootstrap.css">

Express routing not working when adding multiple placeholders

Hi I am studying node js, meanwhile I am facing this issue.
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
/*This route is working fine */
app.get("/:username", function (req, res) {
res.sendFile(__dirname + "/public/ui/" + "user.html");
});
/*This route is not working */
app.get("/:username/:id", function (req, res) {
res.sendFile(__dirname + "/public/ui/" + "user.html");
});
My folder Structure is
-server
-public
-ui
-ext (external files folder)
- images(all images folder)
-js (My js files folder)
-style (my css folder)
-user.html
-index.js
-user.js
When I am trying to load url http://localhost:8888/stranger/19, my page is loading but none of the files specified in user.html is not loading.
It seems like url of my css file is http://localhost:8888/stranger/ui/style/main.css instead of http://localhost:8888/ui/style/main.css.
This is happening for all files loading via ui. ("http://localhost:8888/stranger" this is coming instead of "http://localhost:8888"). How can I fix this issue
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="ui/ext/bootstrap-3.3.4/css/bootstrap.min.css" >
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="ui/style/main.css" >
<script src="ui/ext/jquery/jquery.min.js" ></script>
<script src="ui/ext/bootstrap-3.3.4/js/bootstrap.min.js" i></script>
<script src="ui/ext/moment.js" i></script>
<script src="ui/js/main.js" ></script>
<script src="ui/js/web.js" ></script>
<script src="ui/js/user_module.js" ></script>
<script src="ui/js/chat_module.js" ></script>
</head>
<body class="pz-main">
</body></html>
Add a route to static file to public directory
app.use(express.static('public'))
Here is the documentation on using the public folder
Then in your html take the path as,
<link rel="stylesheet" type="text/css" href="/ui/style/main.css">
Here are the working codes:
your app.js or server.js where the express is defined
var express = require('express');
var app = express();
app.use(express.static('public'))
app.get("/:username", function (req, res) {
res.sendFile(__dirname + "/public/ui/" + "user.html");
});
app.get("/:username/:id", function (req, res) {
res.sendFile(__dirname + "/public/ui/" + "user.html");
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
})
Your user.html in public/ui direcrtory.
<html>
<head>
<link rel="stylesheet" type="text/css" href="/ui/style/main.css">
</head>
<body>
Page will be in green color due to css
</body>
</html>
Your css in public/ui/style directory.
body{
background: green;
}
Follow these steps and it will work.
The problem is with href attribute.
Your current href attribute in link tag is:
<link rel="stylesheet" href="ui/ext/bootstrap-3.3.4/css/bootstrap.min.css" >
Which means to use current url as base url. Change it to following:
<link rel="stylesheet" href="/ui/ext/bootstrap-3.3.4/css/bootstrap.min.css" >
Simply add / at the start and it should fix the problem.

Files inside the assets folder are not being loaded in sub pages

I have a folder structure like below
assets
bootstrap
css
style.css
js
jquery.min.js
views
partials
head.ejs
header.ejs
scripts.ejs
home.ejs
user_registration.ejs
In my app.js file I have set this assets folder like:
var app = express();
app.use('/static', express.static('assets'));
var routes = require('./routes/routes');
In my routes.js file
exports.userLogin = function(req, res){
var userLogin = req.params.userId;
var users = memberData.users;
res.render('user_registration', {
title : 'Welcome',
users : users
});
};
In my head.ejs file
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="static/bootstrap/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="static/css/style.css" type="text/css">
Now inside in user_registration file, I have following code
<!DOCTYPE html>
<html lang="en">
<head>
<% include partials/head.ejs %>
</head>
<body>
<% include partials/scripts.ejs %>
</body>
</html>
By using this my jQuery, bootstrap files that are inside assets folder are not being loaded. But the home.ejs page is working normally.
When I check at the console, the home.ejs page is taking those files in following format
http://localhost:3000/static/bootstrap/css/bootstrap.min.css
whereas user_registration page is taking following format
http://localhost:3000/user_registration/static/bootstrap/css/bootstrap.min.css
I am very new in express.js framework, so I could not figure out how to solve this problem. Can anybody please help me. Thank you.
Problem is here app.use('/static', express.static('assets')); in your code line.
Replace it with
app.use(express.static(path.join(__dirname, 'assets')));
And in your head.ejs file replace bootstrap css calling line
href="static/bootstrap/css/bootstrap.min.css" to href="/bootstrap/css/bootstrap.min.css"
Hop you understand.
The problem is: the href link to static resource should be absolute, not relative. Specifically, in head.ejs it should be:
href="/static/bootstrap/css/bootstrap.min.css"
...
href="/static/css/style.css"
NOT:
href="static/bootstrap/css/bootstrap.min.css"
...
href="static/css/style.css"
As app.use('/static', express.static('assets')); stated, the static assets are hosted under /static namespace (absolute URL starting with /static), it doesn't make any sense to use relative URL any more.

Angular 2 incorporating MEAN stack issue

I am trying to attach a backend to my angular 2 application. I have a Server.js file that grabs my index.html but I get an error at my System.import('app').catch(function(err){ console.error(err) }); in my index.html
error
SCRIPt5009: 'System' is undefined
index.html
<html>
<head>
<base href="/">
<title>LGR</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
<link rel="stylesheet" href="./app/css/lgr.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err) }); <----ERROR HERE!
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
server.js
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
var path = require('path');
mongoose.connect('mongodb://localhost:27017/LGR_db');
app.use('app', express.static(__dirname + "/app"));
app.use('node_modules', express.static(__dirname + "/node_modules"));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, '../LGR', 'index.html'));
});
app.listen('3000', function () {
console.log("Server is running on localhost:3000");
});
I am pretty lost here and any help would be great. I guess I don't understand how to "define" system??
edit: added folder structure
Network output
I would say it's because you are sending the index.html file specifically, and doing a static serve for the stuff in /app. If the systemjs.config.js file was in the /app folder and referenced in the index.html as src='/app/systemjs.config.js' it may work.
-- EDIT: Still not 100% sure what the issue is. I did everything we discussed in it and nothing else. Glad it working though!

Resources