Node.js: serve static resources issue on OpenShift - node.js

On OpenShift I created basic node0.10 cartridge and have node_modules folder from which I am trying to get certain files in my index.html but it just gives me 404 http errors.
index.html imports look the following way:
<script src="es6-shim/es6-shim.min.js"></script>
<script src="systemjs/dist/system-polyfills.js"></script>
<script src="angular2/es6/dev/src/testing/shims_for_IE.js"></script>
<script src="angular2/bundles/angular2-polyfills.js"></script>
<script src="systemjs/dist/system.src.js"></script>
<script src="rxjs/bundles/Rx.js"></script>
<script src="angular2/bundles/angular2.dev.js"></script>
Then I have server.js where I am requiring app.js:
...
var app = express();
require('./app.js').setApp(app);
...
app.js looks like this:
var express = require('express');
var app = express();
var path = require("path");
exports.setApp = function (app) {
app.use(express.compress());
var oneDay = 86400000;
app.use(express.static(path.join(__dirname + '/node_modules'), { maxAge: oneDay }));
app.use(express.static(path.join(__dirname + '/'), { maxAge: oneDay }));
};
What could be the issue? Why OpenShift can not access static files in node_modules folder and its subfolders?

This is simple, server cannot read the files through static folders that you pointed in the html until you app.use() them.
Add one line in your server.js
Inside the self.initializeServer = function() {}
self.app.use(express.static(__dirname + '/public'));
According to code above, change the html to
<script src="/public/js..."></script>
The same thing is
self.app.use('/', express.static(__dirname + '/web'));
Will need to change the path to:
<script src="/js..."></script>
Read this article for more information about server.js

Related

Run HTML file on HTTPS local server [duplicate]

I want to serve index.html and /media subdirectory as static files. The index file should be served both at /index.html and / URLs.
I have
web_server.use("/media", express.static(__dirname + '/media'));
web_server.use("/", express.static(__dirname));
but the second line apparently serves the entire __dirname, including all files in it (not just index.html and media), which I don't want.
I also tried
web_server.use("/", express.static(__dirname + '/index.html'));
but accessing the base URL / then leads to a request to web_server/index.html/index.html (double index.html component), which of course fails.
Any ideas?
By the way, I could find absolutely no documentation in Express on this topic (static() + its params)... frustrating. A doc link is also welcome.
If you have this setup
/app
/public/index.html
/media
Then this should get what you wanted
var express = require('express');
//var server = express.createServer();
// express.createServer() is deprecated.
var server = express(); // better instead
server.configure(function(){
server.use('/media', express.static(__dirname + '/media'));
server.use(express.static(__dirname + '/public'));
});
server.listen(3000);
The trick is leaving this line as last fallback
server.use(express.static(__dirname + '/public'));
As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.
For example this line shows that index.html is supported
https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140
In the newest version of express the "createServer" is deprecated. This example works for me:
var express = require('express');
var app = express();
var path = require('path');
//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); // "public" off of current is root
app.listen(80);
console.log('Listening on port 80');
express.static() expects the first parameter to be a path of a directory, not a filename. I would suggest creating another subdirectory to contain your index.html and use that.
Serving static files in Express documentation, or more detailed serve-static documentation, including the default behavior of serving index.html:
By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.
res.sendFile & express.static both will work for this
var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(public, 'index.html'));
});
app.use('/', express.static(public));
app.listen(8080);
Where public is the folder in which the client side code is
As suggested by #ATOzTOA and clarified by #Vozzie, path.join takes the paths to join as arguments, the + passes a single argument to path.
const path = require('path');
const express = require('express');
const app = new express();
app.use(express.static('/media'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'media/page/', 'index.html'));
});
app.listen(4000, () => {
console.log('App listening on port 4000')
})
If you have a complicated folder structure, such as
- application
- assets
- images
- profile.jpg
- web
- server
- index.js
If you want to serve assets/images from index.js
app.use('/images', express.static(path.join(__dirname, '..', 'assets', 'images')))
To view from your browser
http://localhost:4000/images/profile.jpg
If you need more clarification comment, I'll elaborate.
use below inside your app.js
app.use(express.static('folderName'));
(folderName is folder which has files) - remember these assets are accessed direct through server path (i.e. http://localhost:3000/abc.png (where as abc.png is inside folderName folder)
npm install serve-index
var express = require('express')
var serveIndex = require('serve-index')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
var port = process.env.PORT || 3000;
/**for files */
app.use(serveStatic(path.join(__dirname, 'public')));
/**for directory */
app.use('/', express.static('public'), serveIndex('public', {'icons': true}))
// Listen
app.listen(port, function () {
console.log('listening on port:',+ port );
})
I would add something that is on the express docs, and it's sometimes misread in tutorials or others.
app.use(mountpoint, middleware)
mountpoint is a virtual path, it is not in the filesystem (even if it actually exists). The mountpoint for the middleware is the app.js folder.
Now
app.use('/static', express.static('public')`
will send files with path /static/hell/meow/a.js to /public/hell/meow/a.js
This is the error in my case when I provide links to HTML files.
before:
<link rel="stylesheet" href="/public/style.css">
After:
<link rel="stylesheet" href="/style.css">
I just removed the static directory path from the link and the error is gone. This solves my error one thing more don't forget to put this line where you are creating the server.
var path = require('path');
app.use(serveStatic(path.join(__dirname, 'public')));
You can achieve this by just passing the second parameter express.static() method to specify index files in the folder
const express = require('express');
const app = new express();
app.use(express.static('/media'), { index: 'whatever.html' })

how to setup node project with the proper paths to bower component files

I am trying to run a sample app chat application from here.sample chat
I have all the node modules and bower components installed. I have all 3 projects running in command prompts without errors. But I cannot figure out why the bower components are not being found? I have done some searching but some of the solutions I found have not worked. other than 404 errors there is no other error messages.
relevant code(I believe). 3 projects total with all of them containing files that refer to paths
I am also working on windows 10
app.js in chat-main-app
var express = require('express'),
path = require('path'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser');
var routes = require('./routes');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', routes.index);
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
// log a message to console!
});
module.exports = app;
index.ejs in same project
<head>
<title>scotch-chat</title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="libs/angular-material/angular-material.css">
<script src="libs/angular/angular.js"></script>
<script src="http://localhost:2015/socket.io/socket.io.js"></script>
<script type="text/javascript" src="libs/angular-animate/angular-animate.js"></script>
<script type="text/javascript" src="libs/angular-aria/angular-aria.js"></script>
<script type="text/javascript" src="libs/angular-material/angular-material.js"></script>
<script type="text/javascript" src="libs/angular-socket-io/socket.js"></script>
<script type="text/javascript" src="libs/angular-material-icons/angular-material-icons.js"></script>
<script src="js/app.js"></script>
chat-server-project
index.js
//Import all our dependencies
var express = require('express');
var mongoose = require('mongoose');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
//Set our static file directory to public
app.use(express.static(__dirname + 'public'));
//Route for our index file
app.get('/', function(req, res) {
//send the index.html in our public directory
res.sendfile('index.html');
});
chat-web-app
server.js
var express = require('express'),
path = require('path'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser');
var routes = require('./routes');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', routes.index);
app.set('port', process.env.PORT || 4000);
var server = app.listen(app.get('port'), function() {
// log a message to console!
console.error('Port at 4k');
});
module.exports = app;
index.ejs in same project
<head>
<title>scotch-chat</title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="libs/angular-material/angular-material.css">
<link rel="stylesheet" href="libs/MaterialDesign/css/materialdesignicons.css">
<script src="libs/angular/angular.js"></script>
<script type="text/javascript" src="libs/jquery/dist/jquery.min.js"></script>
<script src="http://localhost:2015/socket.io/socket.io.js"></script>
<script type="text/javascript" src="libs/angular-animate/angular-animate.js"></script>
<script type="text/javascript" src="libs/angular-aria/angular-aria.js"></script>
<script type="text/javascript" src="libs/angular-material/angular-material.js"></script>
<script type="text/javascript" src="libs/angular-socket-io/socket.js"></script>
<script type="text/javascript" src="libs/angular-material-icons/angular-material-icons.js"></script>
<script src="js/app.js"></script>
By default, bower uses the directory bower_components, and this should be inside your solution root folder. The directory can be overridden on the bower config file .bowerrc (try to look for it on your solution root folder.
I assume you ran the command bower install within your solution root folder, so, it must be somewhere, otherwise, bower install, will close without changes. If you want to make it install again use the command:
bower install --force
Please make sure that you have git (some packages and dependencies may require) and node installed, access the solution root path and run the following commands:
npm install
(assuming that one of the packages will be bower) run:
bower install
if not run:
npm install bower -g (to install globally and so that you can run bower from any folder) then;
npm install bower (to install on your solution) then;
bower install
All packages and their dependencies should be installed.
To more information about bower package manager, please refer to bower and about .bowerrc and other options refer to bower configuration.
on the repo you mentioned scotch.io, if you browse to the the scotch-chat-main-app you'll see that a file named .bowerrc is present, checking it you will see:
{
"directory" : "app/public/libs",
"proxy":"http://127.0.0.1:8080",
"https-proxy":"http://127.0.0.1:8080",
"strict-ssl" : false
}
So, all bower packages will be installed on that directory.
Note: since you're using windows 10, make sure you run all the installs mentioned above in a terminal windows with Administrator privileges.
If you're running node / express under iisnode, there are some catches.. you don't mention it, so I will assume that you're not, so, to run the solution, just run the command:
gulp run
Let me know how it went.

Cannot GET / Express ERROR

I am learning Mean.js stack, and try to build an app. I have installed Express, and it works. When I tried to configure my static file ( html, js, images, etc.), then things broke.
Here are my files:
server.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + "public"));
app.listen(3000);
console.log('Server running on port 3000');
My html file is very simple :
<!DOCTYPE>
<html>
<head>
<title>Contact List App</title>
</head>
<body>
<h1>Contact List App</h1>
</body>
</html>
So when I start the server : node server.js, and then I type http://localhost:3000/ in the browser, I get the "Cannot Get" error.
Where is the problem?
__dirname doesn't have a trailing slash, so you need to provide one yourself when building the static root:
app.use(express.static(__dirname + "/public"));
^ this needs to be there
You need to make sure the route exists. Also, it is a better practice to use path for joining strings. Also, make sure the directory public exists and the file index.html is inside that folder.
var path = require('path');
var express = require('express');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('index.html');
});
app.listen(3000);
console.log('Server running on port 3000');

Nodejs / Expressjs Cannot link to css file

I am trying out node / express js and created a little web project.
I have the views in root /views directory
so:
root
/views
/css
I've added this to /views/index.html file:
<link rel="stylesheet" type="text/css" href="css/style.css" />
And this is my server.js file code:
var express = require("express");
var app = express();
var router = express.Router();
var path = __dirname + '/views/';
var path = __dirname + '/css/'; //Not working
router.use(function (req,res,next) {
console.log("/" + req.method);
next();
});
router.get("/",function(req,res){
res.sendFile(path + "index.html");
});
router.get("/about",function(req,res){
res.sendFile(path + "about.html");
});
router.get("/contact",function(req,res){
res.sendFile(path + "contact.html");
});
app.use("/",router);
app.use(express.static('public'));
app.use("*",function(req,res){
res.sendFile(path + "404.html");
});
app.listen(3000,function(){
console.log("Live at Port 3000 - http://localhost:3000");
});
How can I get it to read my css files?
To serve static files using Express.JS, use its built-in express.static middleware.
Assuming following directory structure:
root/
server.js
css/
styles.css
All you need is the following code in your server.js file:
var express = require('express');
var app = express();
// key line! - serve all static files from "css" directory under "/css" path
app.use('/css', express.static('css'));
app.listen(3000, function() {
console.log('Live at Port 3000 - http://localhost:3000');
});
To make styles.css available under localhost:3000/css/styles.css address (and analogically for all other files kept in css directory).

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