Express.js + HTML5 appcache not working in Firefox - node.js

I want to use HTML5 app cache in my MEAN app but I can't make it work in Firefox 36. It works in Chromium as expected. This is my file structure:
client
app.js
manifest.appcache
views/
index.html
about.html
server.js
index.html:
<!DOCTYPE html>
<html manifest="/manifest.appcache">
<head>
<meta charset="UTF-8">
</head>
<body>
About
</body>
</html>
manifest.appcache:
CACHE MANIFEST
#0
CACHE:
views/about.html
app.js
server.js:
var http = require("http");
var express = require("express");
var app = express();
app.get("/manifest.appcache", function (req, res) {
res.set("Content-Type", "text/cache-manifest");
res.set("Cache-Control", "no-store, no-cache");
res.set("Expires", "-1");
res.sendFile("/client/manifest.appcache", {root: __dirname});
});
app.get('/', function (req, res) {
res.sendFile('/client/views/index.html', {root: __dirname});
});
app.use(express.static(__dirname + '/client', { maxAge: 31557600000 }));
app.listen(8080);
When I go to localhost:8080, Firefox successfully fetches the manifest (which is not visible in the network tab of dev tools) but it does not store the files in the app cache (Preferences - Advanced - Network shows 0 bytes). It loads them from the standard system cache (I get 304).
I suspect that my routing somehow breaks the links in manifest.appcache but I had to prevent the manifest to be cached itself. I'm not an expert on Node.js and I'm confused by the fact that Chromium and Firefox behave differently. Any help will be appreciated.

Related

Why is app.use() not serving up the 'public' directory when I save even though the path is appears to be correct?

I'm following a slightly outdated tutorial on node and express, and my code is identical to the tutorial, but app.use is not serving up the public directory as I wish. When I go to the root localhost:3000 I still see Weather like in the tags on line 19. When I delete it, I don't see anything, including the public directory's index.html file.
Here is my index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge"> -->
<title>Document</title>
</head>
<body>
<h1>From a static file.</h1>
</body>
</html>
Here is my app.js script:
/* nodejs script that will create, configure, and start the server.
run script: node src/app.js
keep server running: nodemon src/app.js
*/
const path = require('path');
const express = require('express');
const app = express();
const publicDirectoryPath = path.join(__dirname, '../public'); // abs path to serve
// STACKOVERFLOW - WHY ISN'T THIS SERVING UP PUBLIC DIRECTORY?
app.use(express.static(publicDirectoryPath)); // serve 'public' directory
// create root route
app.get('/', (req, res) => {
res.send('<h1>Weather</h1>');
});
// create a help route
app.get('/help', (req, res) => {
res.send([
{name: 'Barack H. Obama'},
{name: 'George W. Bush'},
{name: 'William J. Clinton'}
]);
});
// create an about route
app.get('/about', (req, res) => {
res.send('<h1>About</h1>');
});
// create a weather route
app.get('/weather', (req, res) => {
res.send({
forecast: 'rain',
location: 'Los Angeles'
});
});
// port 3000 is common development port, starts server
app.listen(3000, () => {
console.log('Server is up on port 3000'); // never displays in browser
});
it should be public instead ..public like this
const publicDirectoryPath = path.join(__dirname, 'public')
As app.js and public share the same parent directory at the same level. So ..public will point out to dir public outside src which is not available.

Stylesheet not loaded, even though statics has been configured

I'm going crazy over this...
I have this simple NodeJS server running - it serves the ./start.html file fine, but the CSS-file is not loaded.
My folder structure looks like this:
/public/css/styles.css
/interface.js (the Node-file)
/start.html
Node is running this code:
const app = express();
const hostname = '127.0.0.1';
const port = 3000;
let serials;
app.use(express.static('public'));
// Make these folders accessible by our HTML-files
app.use('/css', express.static(__dirname + '/public/css'));
//app.use('/js', express.static(__dirname + '/public/js')); // Not used at the moment
//app.use('/images', express.static(__dirname + '/public/images')); // Not used at the moment
app.get('/start', (req, res) => {
const fs = require('fs');
var content;
// We load the file asynchronously and pass on the content to the screen when loaded.
fs.readFile('./start.html', function read(err, data) {
if (err) {
throw err;
}
res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Length': data.length, 'Expires': new Date().toUTCString()});
res.end(data);
});
});
The start.html file looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>start</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<link href="css/styles.css" rel="stylesheet" type="/text/css">
<script type="text/javascript">
$(document).ready(function() {
etc...
When accessed, using localhost:3000/start, it only shows the HTML-code.
When opening localhost:3000/css/styles.css it displays the stylesheet just fine.
The browser console also does not show any CSS-file loaded.
Any suggestions, please?
Simple mistake: the CSS linkage had a "/text/css" instead of "text/css" and not an error in the JS after all. Now it works perfectly.

Cant load css file

I'm trying to use the login templates (Took from: 50 Free HTML5 And CSS3 Login Forms For Your Website 201
My directory set up is like this :
-css
|
-- style.css
- js
|
-- index.js
|
index.html
The head of the index.html file looks:
<head>
<meta charset="UTF-8">
<title>Sign-Up/Login Form</title>
<link href='http://fonts.googleapis.com/css?family=Titillium+Web:400,300,600' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
and the body contains the includes scrips:
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
My node.js looks:
// Import Required Module
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
// css
var path = require('path')
app.use(express.static(path.join(__dirname, 'public')));
// Create instances
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Get
app.get('/', function (req, res) {
console.log('Get: /');
res.sendFile('LoginTemplate/index.html', {root: __dirname })
})
/*
app.get('css/style.css', function (req, res) {
console.log('Get: css/style.css');
res.sendFile('css/style.css', {root: __dirname })
})
*/
// Listner
app.listen(3001, function () {
console.log('Example app listening on port 3001!')
})
When loading the html file I'm getting the error:
GET http://127.0.0.1:3001/css/style.css
I have tried to look for solution at:
Can not get CSS file
And created the public folder and copy the css folder inside, but it still doesnt work.
How can I load the css & js files ?
// Import Required Module
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
// Create instances
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Get
app.get('/', function (req, res) {
console.log('Get: /');
res.sendFile('LoginTemplate/index.html', {root: __dirname })
})
app.get('/css/style.css', function (req, res) {
console.log('Get: css/style.css');
res.sendFile('LoginTemplate/css/style.css', {root: __dirname })
})
app.get('/js/index.js', function (req, res) {
console.log('Get: js/index.js');
res.sendFile('LoginTemplate/js/index.js', {root: __dirname })
})
// Listner
app.listen(3001, function () {
console.log('Example app listening on port 3001!')
})
Everything looks good in your code and folder setup. From the URL you are posting (http://127.0.0.1:3001/css/style.css), I am guessing that the error lies in your server instance. Check the definition files and make sure that the server has permission to read css/style.css.
I have run into this problem when the file and folder do not have the right permissions. A quick check for this is running something similar to sudo chmod -R 0777 [path_to_your_project] (linux and Mac systems will use this command). This command gives full access to all users and guests to read, write and execute your files and is a quick way to verify whether the problem is user rights.
I have also run into this same problem when my web server is not correctly configured. In those cases, I had accidentally allowed the web server to share all files in the root folder (eg: /var/www ), but not any sub folders, so (using the example) the folder /var/www/images would be parsed by the web server and seen as an area that is protected. In this case, the Web Server has access, but it refuses to serve the files based on the configuration rules.
I hope one of these two fixes helps direct you down the right path to a solution.
Good luck!

angularJS with nodeJS

at last time I have learn use AngularJS and NodeJs, but I have a few problems.
First:
I'd like loading.. for instance index.html or other file, now I do this manual and simplest how I can, but even then I have problem with type file which are include in index.html I receive:
Resource interpreted as Stylesheet but transferred with MIME type text/html:...
How can I correct this ?
below code.
'use strict';
var http = require('http');
var fs = require('fs');
var mysql = require('mysql');
var render = function(response, fileName, code, httpCode){
var code = code || 'utf8';
var httpCode = httpCode || 200;
fs.readFile(fileName, code, function(err, data){
if(err) { return console.log(err); }
response.writeHead(httpCode, {'Content-type': 'text/html; charset='+code});
response.write(data);
response.end();
});
};
http.createServer(function(req, res){
render(res, 'index.html');
}).listen(9999, '127.0.0.1');
console.log('Server running');
html:
<!doctype html> <html class="no-js"><head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" type='text/css' href="styles/main.css">
</head><body></body></html>
Can I use nodejs server with gruntjs ? if yes, how I can do it ?
Do somebody know any tutorial only angular + node ? it's mean I know quite good angularJS, but I can't use it with nodeJS..
The problem is that your browser requested a css file and you returned a file with the MIME type text/html. You would have to handle all the possible types of files (js, html, txt, css, ...).
I would recommend you to use an existing module like express, which will save you a lot of time. After installing express, initalize a static file server by doing following:
server.use(express.static(__dirname + '/public'));
This is how my folder structure look like of Angular JS + Node JS (with Express JS)
ProjectTitle
|_app
|_bower_components
|_images
|_scripts
|_styles
|_views
|_index.html
|_favicon.ico
|_routes
|_test
|_.bowerrc
|_.jshintignore
|_.jshintrc
|_bower.json
|_Gruntfile.js
|_package.json
|_README.md
|_server.js
3 imp things to notice here
/app - contains angular static app including all its dependant styles, scripts & images
/app/script - angular javascript files
/server.js - node js web server code, here is sample code
var express = require('express'),
http = require('http'),
path = require('path');
var app = express();
// all environments
app.configure(function() {
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev'));
app.use(express.static(path.join(__dirname, 'app'))); // here you are mentioning which directory should be static directory for the project, in this case 'app'
app.use(express.favicon());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
});
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
Start node js server using
$ node server.js
It will start express server, and you can access it by typing in browser window
localhost:3000
It will be good to look at Yeoman and install Angular Generator. This is just to setup proper angular js project without error. If you have your own structure thats fine.

less-middleware not compiling, getting 404

I have a node.js server running with less-middleware. From my understanding, it compiles on the fly and places the css file in the destination/same(if not specified) folder.
My problem is I'm getting a 404 error on the get request for the css file:
Err: GET http://webserver/public/less/blog-reset.css 404 (Not Found)
Here is what I'm working with:
web.js
//requiring dependencies
var express = require("express");
var logfmt = require("logfmt");
var lessMiddleware = require('less-middleware');
var hogan = require('hogan-express');
var path = require('path');
//all environments
var app = module.exports = express();
var port = Number(process.env.PORT || 5000);
app.use(logfmt.requestLogger());
app.use(lessMiddleware(path.join(__dirname,'public')));
app.use(express.static(path.join(__dirname,'public')));
app.set('layout',path.join(__dirname,'src','views','blog-layout'));
app.enable('view cache');
app.engine('.html',hogan);
//page routing called after env loads
require('./src/router');
//listening port
app.listen(port, function() {
console.log("Listening on " + port);
});
blog-layout.html
<head>
<title>EpiBlog</title>
<link href='/public/less/blog-reset.css' rel='stylesheet' type='text/css'/>
</head>
<body>
{{{yield}}}
</body>
directory layout
ROOT
public
less
src
web.js
Versions
less-middleware v0.2.1-beta
express v4.0.0
What I've tried:
using app.use(lessMiddleware)({ src: __dirname + '/public' })); (apparently the old way of doing it)
using app.use(lessMiddleware(path.join(__dirname,'public','less')));
moving app.use(express.static(path.join(__dirname,'public'))); from web.js to router.js
toying with different paths
moving contents of router.js to web.js
specifying the destination using
this:
app.use(lessMiddleware(path.join(__dirname, 'source', 'less'), {
dest: path.join(__dirname, 'public')
}));
the problem was:
<link href='/public/less/blog-reset.css' rel='stylesheet' type='text/css'/>
should have been:
<link href='/less/blog-reset.css' rel='stylesheet' type='text/css'/>
i read that:
link(rel='stylesheet', type='text/css', href='css/styles.css')
was paired with directory structure:
myapp
+-public
+-css
+-styles.less
which led me to believe that this call:
app.use(express.static(path.join(__dirname,'public')));
makes the request assume /public/ is the parent so i was being redundant calling /public/less/blog-reset.css
reference was found here: express.js less compiler: can not get work

Resources