Bootstrap examples with Express.js - javascript

I'm trying to get Bootstrap Carousel example to work with simple Express.js code, but I failed with always 404 returned code for those reference links in the html file. The index.html resides in /test/ folder, while the rest of the reference files are located in /test/docs/assets/js and /test/docs/assets/ico.
The Express.js simple code is as below:
app.get('/', function(request, response) {
response.sendfile('index.html');
});
The reference link part in the index.html is like:
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="./docs/assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="./docs/assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="./docs/assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="./docs/assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="./docs/assets/ico/favicon.png">
I've tried with a different html file without the reference link and it works well. I also tried to tweak with something like app.use(express.static(__dirname + '/docs/assets/ico/')) but it doesn't work either.
How should I do to get it work correctly? I also found there isn't much examples about express.js; would you have any suggestion of the resources for study?
Thanks in advance.

If your directory structure looks like this:
app.js
index.html
docs/assets/ico/
Then try this as a minimal Express app:
// app.js
var express = require('express');
var app = express();
app.use(express.static(__dirname));
app.listen(8000);
Some explanation:
__dirname is the directory in which app.js resides; since index.html and your asset files are located relative to that directory, we'll use that as the 'root' directory for express.static;
you don't need a separate route for / if you have an index.html, because the static middleware will 'translate' a request for a directory to an index.html file in that directory;
EDIT: if you want to keep the separate route for /, make sure you include it before you include the static middleware. The reason for this is that middleware and routes are (generally) called in order of declaration; if you include the static middleware first, it will get to handle the requests for / and it will never reach your route handler:
// WRONG:
app.use(express.static(...));
app.get('/', ...);
// RIGHT:
app.get('/', ...);
app.use(express.static(...));

Related

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

I am new to Google App Engine and I'm trying to get the project I've been running locally hosted there.
My index.html file shows up, but it is not applying the CSS to it. I'm not exactly sure what a MIME type is, and I'm not exactly sure where in my code it's trying to get this from. I just assumed that it would just load the tag that I have in my HTML content and apply it like how it did while using browsersync. File index.html is loaded via:
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/index.html'));
});
CSS being loaded in file index.html:
<link rel="stylesheet" type="text/css" href="style.css">
When you're returning the stylesheet from the server, you should set the content-type attribute for the header to text/css i.e. you should have something like
<link href="style.css" rel="stylesheet" />
app.get('/style', (req, res) => {
res.setHeader('Content-Type', 'text/css');
res.sendFile(path.join(__dirname, '/style.css'));
});
app.get('/', (req, res) => {
res.setHeader('Content-Type', 'text/html');
res.sendFile(path.join(__dirname, '/index.html'));
});
Permanent fix:
File server.js
app.use(express.static('./public'));
And move all your static resources to a public directory in your project. Then your HTML content is valid.
Source
The issue could probably be with the CSS library starting with comments.
In development, if the style sheet is started with some comments, it could be seen as something different from CSS.
Removing the library and putting it into a vendor file, may solve the issue.
Another possibility for Node.js applications is that you should check your configuration.
Example:
app.use(express.static(__dirname + ‘/public’));
Notice that /public does not have a forward slash at the end, so you will need to include it in your href option of your HTML:
Example:
href=”/css/style.css”>
If you did include a forward slash /public/, then you can just do href=”css/style.css”>.
Be sure that the CSS name is style.css without the second "s" at the end. That could also cause the issue.

Why is styles.css showing canceled in Developer Tools?

I'm trying to send my 'index.html' file as a response to my local server and within that index.html, there is a link to an external CSS file.
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req,res){
res.sendFile(__dirname+"/index.html");
});
and I've included the link in HTML head element like below:
<link href="styles.css" rel="stylesheet" >
Now the problem is that the 'styles.css' file is not loading up on the page. And on the Network section of the Chrome developer tools, it is showing status: canceled in front of the 'styles.css'.
Here is the screenshot of the canceled status showing for styles.css
Why is this happening and what is the solution to it? I've tried other people's solution of deleting the cache, but it doesn't work.
EDIT: Here, I have the exact same problem , and I've tried their solutions too, but it won't work
EDIT2: As I tried #wilkoklak's solution , It's still the same error
I just added the whole thing from the Bootstrap examples so don't really think that would be a problem
You have to serve the css file as well!
You can do this by using express.static
Create a folder named css and move your styles.css there
Your project structure would look similiar to this
project/
css/
styles.css
server.js
index.js
Then add this middleware:
app.use(express.static('css'))
This middleware will look for any match with files inside css folder, and send them in response.
When you GET / (when you open your webpage), the browser also sends GET /styles.css to your server. There was no route handler for /styles.css in your app. express.static does that for you
The problem of css not being loaded can be solved by using express.static and a dedicated static folder (Example: www) for static files.
Here is the working example using express.static:
Step 1: Put static files (index.html, styles.css in a static folder named www)
Folder structure:
/nodejs-web-demo
--> server.js
/www
--> index.html
--> styles.css
Step 2: Create the index.html and styls.css files in www (static) folder
File name: www/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/styles.css">
<title>Expressjs website</title>
</head>
<body>
<p class="my-style">Hello! How are you doing?</p>
</body>
</html>
File name: www/styles.css
.my-style{
color: blue;
}
Step 3: Use express.static to serve files from static folder
const http = require('http')
const express = require('express')
const path = require('path')
const app = express()
app.use(express.static("www"))
app.use('/', function(req,res) {
res.sendFile(path.join(__dirname + '/www/index.html'))
})
const server = http.createServer(app)
const port = 3000
server.listen(port)
console.log('Web server started on port # ' + port)
Output:
> node server.js
Web server started on port # 3000

express.static() not serving files from public folders in router paths that are not "/"

Express.static config:
app.use(express.static(__dirname + "/public"));
File Structure:
--public
--assets
--js
--[js scripts]
--stylesheets
--[css files]
Routes:
const shopRoutes = require('./routes/shopRoutes')
app.use('/', shopRoutes)
const itemApiRoutes = require('./routes/itemApiRoutes')
app.use('/api/shopitems', itemApiRoutes)
const logSignRoutes = require('./routes/logSignRoutes')
app.use('/account', logSignRoutes)
The issue is that all ejs files in the root path at "localhost:3000/" (shopRoutes) calls for the following css file like so and works perfectly fine:
<link rel="stylesheet" type="text/css" href="stylesheets/header.css">
Using Express Router, the ejs file at the path "localhost:3000/account/login" calls for the same css file with the exact same syntax but gets the error:
Cannot GET /account/login/stylesheets/header.css/
Am I not understanding how express.static serves static files or am I doing something incorrectly?
If you specify a relative URL such as:
href="stylesheets/header.css"
then the browser adds the path of the web page you're in to that and requests that combined path from your server. Unless your web page is at the top level of your web site and thus has no path, it will not work properly. I want to emphasize, this is the browser doing this, not Express. So, if you're in a web page with this URL:
http://localhost:3000/account/login
And, the browser sees:
<link rel="stylesheet" type="text/css" href="stylesheets/header.css">
It will end up combine the path of the web page
/account/login
with the relative URL you in <link> tag and as you've found out, it will request:
/account/login/stylesheets/header.css
When, express.static() sees that URL, that will not match anything in your
__dirname + "/public"
directory hierarchy so it will not be found.
Instead, you want to specify a leading slash:
<link rel="stylesheet" type="text/css" href="/stylesheets/header.css">
That tells the browser not add any path to the URL and it will send a request to your server for:
/stylesheets/header.css
When express.static() gets that request, it combines that with
__dirname + "/public"
and will end up looking for a file
__dirname + "/public" + "/stylesheets/header.css"`
which will be found in your public directory hierarchy and will work.

Resource interpreted as Stylesheet but transferred with MIME type text/html in AngularJS

Have an angular application:
This is part of my index.html page:
<!DOCTYPE html>
<html lang="en" ng-app="ReApp">
<head>
<meta charset="UTF-8">
<title>REApp</title>
<link rel="stylesheet" href="./lib/bootstrap/dist/css/bootstrap.min.css">
<script src="./lib/angular/angular.min.js"></script>
</head>
<body></body>
</html>
This is part of my server.js(start point):
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.use('/api', api);
app.get('*', function(req, res){
res.sendFile(__dirname + '/public/app/views/index.html');
});
Problem is: when i have one route (localhost:3000/first) everything working. When i have route something like that: localhost:3000/first/second, i have an error "Resource interpreted as Stylesheet but transferred with MIME type text/html". In the terminal i have get request - first/second/lib/angular/angular.min.js. Of course i don't have that link. May who knows how to set a start page for this links in undex.html?
To fix this issue all you have to do is place the <base href="/"> element just below the <title> element in the head section of index.html page.
In my case, I was using packages installed by bower (the same should work for npm or yarn or any other package manager installed packages as well).
Add this middleware somewhere in your express code, before any other route declarations.
app.use('/assets', express.static(path.join(__dirname + '/bower_components')));
The first argument /assets is just a virtual path that doesn't have to exist in your project, and the second one is telling express to serve static assets from the bower_components folder.
Next, in your markup, have your stylesheet inclusions like the following:
<link rel="stylesheet" href="/assets/bulma/css/bulma.min.css">

Serving static files from Node.js

I'm trying to serve static files from Node.js the only problem I'm having, is if I keep going into sub paths, like so:
localhost:3000/foo/bar/baz/quux
Then I have to step up the same amount of times, like this:
../../../../public/javascripts/whatever.js
As you can see that gets really annoying, is there a way to make Express v3 just know so that I can just do /public/javascripts/whatever.js instead of having to step up? Thanks in advance
This is my current static middleware for Express`
app.use("/public", express.static(__dirname + '/public'));
If you reference your static files from the root (i.e. src='/some/path/to/file.js'), the url should not matter.
Example Website using Static Routing
Directory Structure
/public
/css/style.css
/js/site.js
/vendor/thoughtbrain/js/awesome-town.js
/views/view.html
/app.js
view.html
<!DOCTYPE html>
<html>
<head>
<!-- These files are served statically from the '/public' directory... -->
<link href="/css/style.css" rel="stylesheet" >
<script src="/js/site.js"></script>
<!-- ... while this is "mounted" in virtual '/public' -->
<script src="/public/js/awesome-town.js"></script>
</head>
<body><p>Express</p></body>
</html>
app.js
var express = require('express'),
http = require('http'),
path = require('path'),
app = express();
// Remember: The order of the middleware matters!
// Everything in public will be accessible from '/'
app.use(express.static(path.join(__dirname, 'public')));
// Everything in 'vendor/thoughtbrain' will be "mounted" in '/public'
app.use('/public', express.static(path.join(__dirname, 'vendor/thoughtbrain')));
app.use(express.static(path.join(__dirname, 'views')));
app.all('*', function(req, res){
res.sendfile('views/view.html')
});
http.createServer(app).listen(3000);
With this application running,
http://localhost:3000
and
http://localhost:3000/foo/bar/baz/quux
both serve view.html and all referenced assets resolve.
Express Framework has a section on the use of static middleware here.
With that static() configuration, Express is already at least capable of finding /public/javascripts/whatever.js.
Though, it does depend on whether your public folder is in the same directory as your script (due to the use of __dirname when specifying the path).
If it is, the URL prefix /public should map to the file-system prefix of ./public (with . being __dirname) so that:
A URL of `/public/javascripts/whatever.js`
Maps to `./public/javascripts/whatever.js`

Categories