express js not serving static files - javascript

I realise that this is a typical question yet after reading similar issues I could not get any solution to work and properly serve my static files with express.
My app folder structure looks like this:
..
-bin
-lib
-run
-etc
-node-modules
-public
--css
---styles.css
---svg.css
--images
---Loading.gif
--javascript
---nav.js
--favicon.ico
--index.html
app.js
My app.js should create a server with express and serve the static files in the 'public' folder. But it seems to only find the 'index.html'.It looks like this:
var express = require('express');
var path = require('path');
var app = express();
app.set('port', 13245);
app.use(express.static(path.join(__dirname, 'public')));
var server = app.listen(app.get('port'), function() {
var port = server.address().port;
console.log('Welcome to the planet on port : ' + port);
});
Finally, my index.html file has a header like this:
<head>
<title>...</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link rel="stylesheet" href="css/styles.css" />
<link rel="shortcut icon" href="favicon.ico"/>
<link rel="apple-touch-icon" sizes="120x120" href="images/Loading.gif"/>
<link rel="apple-touch-icon" sizes="152x152" href="images/Loading.gif"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">//JQuery</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">//Bootstrap min</script>
<script src="javascript/nav.js"></script>
</head>
but css and js files do not seem to be served.
It may be me but I don't see what I did wrong so just wondering.
the errors I get are
GET example.com/css/styles.css 404 (Not Found)
GET example.com/javascript/nav.js

I have a similar setup as you. My app.js file is in the same folder as my public folder. And this works for me.
app.use(express.static('public'));
I don't think you need the __dirname and join, since __dirname references the directory that the current script is running from, but the public folder is already in your root directory.

Thanks for your answers.
I solved this issue by adding the folder path where my application was in the urls.
So for
.MyAppFolder
-bin
-lib
-run
-etc
-node-modules
-public
--css
---styles.css
---svg.css
--images
---Loading.gif
--javascript
---nav.js
--favicon.ico
--index.html
app.js
I just had the same app.js file
var express = require('express');
var path = require('path');
var app = express();
app.set('port', 13245);
app.use(express.static(path.join(__dirname, 'public')));
var server = app.listen(app.get('port'), function() {
var port = server.address().port;
console.log('Welcome to the planet on port : ' + port);
});
and urls in the index.html file are like this:
<link rel="stylesheet" href="/MyAppFolder/css/styles.css" />
Problem solved! ;)

Sipmly add this / before ur path to css and js files so ur link should look like this:
<link rel="stylesheet" href="/css/styles.css" />
I hope that will help

You can add a base href to you HTML document head.
<head>
<title>...</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<base href="http://localhost:13245" />
<link rel="stylesheet" href="css/styles.css" />
<link rel="shortcut icon" href="favicon.ico"/>
<link rel="apple-touch-icon" sizes="120x120" href="images/Loading.gif"/>
<link rel="apple-touch-icon" sizes="152x152" href="images/Loading.gif"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">//JQuery</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">//Bootstrap min</script>
<script src="javascript/nav.js"></script>
</head>

Related

Host an Angular app in OpenLiteSpee Web Server

I am trying to host my angular app into my OpenLiteSpeed but I am not getting anything.
To create the app for production I use: ng build --prod, automatically it creates all the files I need in the dist folder.
Next, I move all these files to my root folder on the server.
Finally, I check if the webpage is working but it doesn't shows anything just the blank page!
The HTML code for the index is:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ConFusion</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles.c3adc567aae88948c2ab.css"></head>
<body>
<app-root></app-root>
<script src="runtime.acf0dec4155e77772545.js" defer></script><script src="polyfills.35a5ca1855eb057f016a.js" defer></script><script src="main.9a959de356bd26498a0e.js" defer></script></body>
</html>

Refused to apply style from 'http://localhost:3000/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type

I am just creating an example website template, and am getting this error in the Chrome console:
Refused to apply style from 'http://localhost:3000/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
I am getting a 404 error when trying to load the css/style.css page, but the path seems correct. Below is some of the basic code for the site:
App:
var express = require('express');
var app = express();
var exphbs = require('express-handlebars');
var path = require('path');
app.engine('hbs', exphbs({extname:'hbs'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(express.static(path.join(__dirname, "static")));
app.get('/', function(req, res) {
res.render('resume.hbs')
})
app.listen(3000)
HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<base href="/">
<link rel="stylesheet" href="..\css\style.css" type = "text/css">
<title>Example Website</title>
<h1>Header</h1>
<hr id = 'headerBorder'>
</head>
<body>
</body>
</html>
CSS:
h1 {
color: blue
}
Below are what the folders look like, which shows the path. I cannot seem to find a way to fix this. Any ideas?
This is likely just caused by not having the expected path.
You're using this line here:
app.use(express.static(path.join(__dirname, "static")));
So in this case, you need a folder named "static" and inside that folder you can put your css and images. You would be able to link to them as follows:
<link rel="stylesheet" href="/css/style.css" type="text/css">
Reference: https://expressjs.com/en/starter/static-files.html
Since you are working with hbs, create "public" folder and keep your static folders, css,javaScript,img inside the "public" folder. then
const path = require("path");
app.use(express.static(path.join(__dirname, "public")));
Here is the magic, since you told express that use "public" as a static folder, when you link the files inside that folder, hbs will take "public" folder as the "root" folder.
So lets say you have main.css in folder "style" inside the folder ""public", "public/style/main.css" directory, when you link main.css:
<link rel="stylesheet" href="style/main.css" type="text/css" />
Also, this is the complete setup for hbs in express:
app.set("view engine", "hbs");
app.engine(
"hbs",
expressHbs({
defaultLayout: "layout",
extname: ".hbs",
layoutsDir: __dirname + "/views/layouts",
partialsDir: __dirname + "/views/partials"
})
);
Place all your css inside a folder - call it static or public.
So your css is located at public/css/style.css.
In your app.js, you would reference static files by:
app.use(express.static(path.join(__dirname, "public")));
The path of the public folder should be relative to the app.js file.
just make a folder called static. and put your css folder and image folder in static folder.
Don't forget to first make css folder to keep all css files and image folder for all images.
your code:
app.use(express.static(path.join(__dirname, "static")));
in this code you are saying express to look at static folder and because you don't have static folder you are getting error and your css and image are not applying on your website.
Sol:
First create a folder static and transfer css folder to static folder.
2.In html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<base href="/">
<link rel="stylesheet" href="css\style.css" type = "text/css">
<title>Example Website</title>
<h1>Header</h1>
<hr id = 'headerBorder'>
</head>
<body>
</body>
</html>
Js file
var express = require('express');
var app = express();
var exphbs = require('express-handlebars');
var path = require('path');
app.engine('hbs', exphbs({extname:'hbs'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(express.static("static"));
app.get('/', function(req, res) {
res.render('resume.hbs')
})
app.listen(3000)
I tried to change the different slashes as well, but that does not entirely solve the problem. Propably, the bootstrap CSS defines h1 already as well. You therefore need to change the order of the CSS files in your HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/style.css" type="text/css">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<base href="/">
<title>Example Website</title>
<h1>Header</h1>
<hr id = 'headerBorder'>
</head>
<body>
</body>
</html>
Adding only !important to your CSS does not solve the issue.

Polymer and NodeJs/ Express server

I am using Polymer combined with a NodeJs/Express server which I am planning on hosting with Firebase functions.
My problem here is that besides the index.html none of the inner files can be found (404). With none of them I am revering to the first imports made inside my index file.(webcomponents-loader.js and the my-app.html)
I tried many different flavours. From absolute paths, with base tag and without and with a different directory structure.
I am clearly not an expert when it comes to node.js or express so I believe I am doing something fundamentally wrong.
Update
The links that can't be found have a different URL then the path that serves my index.html
404: http://localhost:5000/src/my-app.html
index: http://localhost:5000/nodefire-96b46/us-central1/serve
My directory:
fire_node
functions
node_modules
index.js
build
modern
bower_components
index.html
polymer.json
src
my-app
My server file
const express = require('express');
const app = express();
app.use(express.static(__dirname + '/build/modern'));
app.get('/', (req, res) => {
res.sendFile("index.html", {root: '.'});
});
app.listen(2000, () => {
console.log('Server is listening on port 2000');
});
My index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
<title>My App</title>
<base href="/modern/">
<link rel="manifest" href="manifest.json">
<script>
window.Polymer = { rootPath: '/' };
</script>
<script src="bower_components/webcomponentsjs/webcomponents-loader.js"></script>
<link rel="import" href="http://localhost:4000/fire_node/functions/build/modern/src/my-app.html">
</head>
<body>
<my-app></my-app>
<noscript>
Please enable JavaScript to view this website..
</noscript>
</body>
</html>

How to add styles(css) and js to handlebar files?

I want to add styles and js to my handlebar files. I tried looking for different places but still not able to find a solution. I tried using partials to store the stylesheet tags then adding those partials to handlebar but that too didn't worked.
(Or if there is any other templating engine that provides much better css support, that too will work for me)
Please Help!
styles.hbs (partial file)
<link rel="stylesheet" href="./../css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="./../css/main.css">
server.js
const express = require('express');
const hbs = require('hbs');
var app = express();
app.set('view engine', 'hbs');
hbs.registerPartials(__dirname + '/views/partials');
app.get('/', (req, res) => {
res.render('index.hbs');
});
app.listen(3000, ()=>{
console.log('Server is up at port 3000');
});
index.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Home Page</title>
{{> styles}}
</head>
<body>
...
</body>
</html>
This is an old question but still confusing. Here is the most effective way to use different css file in your views:
main.hbs (Your base layout)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="mainstyle.css">
<!-- mainstyle.css will be effective in all pages-->
{{{customstyle}}}
<title>{{title}}</title>
</head>
<body>
{{body}}
</body>
</html>
Please pay attention {{{customstyle}}} line in main.hbs
app.js
...
app.use((req, res) => {
res.status(404).render("404page", {title:"404 not found",
customstyle: `<link rel="stylesheet" href="/css/customstyle.css">`});
});
...
Thats it. As you know, {{{ }}} renders as html code, but {{ }} renders as only text in handlebars. customstyle passes as an argument to main.hbs layout file. We used three curly brackets in main.hbs file, because of we wanted to process the argument we send as html code. In this way, customsytle.css file added only when 404page viewed.

NodeJS and ExpressJS - Javascript files load but CSS files don't

I am building a web app using NodeJS, ExpressJS, AngularJS, Bootstrap, and a Postgres DB using Sequelize. I am having problems with loading all of my "asset" files when I load up my index.html page.
So here is my structure:
server.js
app
index.html
app.js
assets
css
styles.css
img
js
javascript files
Here is my server.js file:
var express = require('express');
var app = express();
var port = process.env.PORT || 5000;
var database = require('./config/database');
var path = require('path');
app.use(express.static(__dirname + '/app'));
require('./api/routes.js')(app);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.listen(port, function() {
console.log("Node app is running at localhost:" + port);
});
Here is my index.html file:
<DOCTYPE html>
<html lang='en' ng-app="app">
<head>
<link src='assets/css/bootstrap.min.css' rel='stylesheet' type='text/css' />
<link src='assets/css/styles.css' rel='stylesheet' type='text/css' />
</head>
<body ng-controller="controller">
<nav class="navbar navbar-inverse navbar-fixed-top">
</nav>
<script src='assets/js/jquery-2.1.3.min.js'></script>
<script src='assets/js/angular.min.js'></script>
<script src='assets/js/angular-route.min.js'></script>
<script src='assets/js/angular-resource.min.js'></script>
<script src='assets/js/bootstrap.min.js'></script>
<script src='assets/js/modernizr.js'></script>
<script src='app.js'></script>
</body>
</html>
My problem is that, with my current setup, when I start up node and hit my localhost:5000 the index.html file loads along with all of my javascript files inside the assets/js folder. When I open up chrome dev tools I can actually see that folder being loaded in the sources pane. However, NONE of my CSS loads. Why is that? Any help would be greatly appreciated as I have basically exhausted all other options.
first post, so be generous. :)
you should actually use href to reference your css files.
<link href='assets/css/bootstrap.min.css' rel='stylesheet' type='text/css' />
<link href='assets/css/styles.css' rel='stylesheet' type='text/css' />
See here: http://matthewjamestaylor.com/blog/adding-css-to-html-with-link-embed-inline-and-import

Categories

Resources