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
Related
I am trying to build the ToDo app with the MEAN stack and I can't get the Express server to connect to Angular 2. I believe it has something to do with where I have my index.html view relative to the Angular installation, but I can't figure it out.
The error I am getting is the HTML on index.html is rendering but not picking up the logic behind the selector so my assumption is my tags are wrong or something. I have tried every which way to adjust the tags, but I can't get it to work when running server.js. I know it is something silly but been working on this for a while.
Server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var todos = require('./routes/todos');
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname,'client'))); //folder where angular will be
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('/api/v1/', todos);
app.listen(3000, function(){
console.log('Server started on port 3000...');
});
Index.html (in Views folder)
<!DOCTYPE html>
<html>
<head>
<title>Angular QuickStart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="src/styles.css">
<!-- 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/systemjs/dist/system.src.js"></script>
<script src="src/systemjs.config.js"></script>
<script>
System.import('src/main.js').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading AppComponent FROM SERVER SIDE content here ...</my-app>
</body>
</html>
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
#NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1>`,
})
export class AppComponent { name = 'Angular'; }
Below are the two errors I am getting in the console:
GET http://localhost:3000/src/app/app.module 404 (Not Found)
scheduleTask # zone.js:1960 ZoneDelegate.scheduleTask # zone.js:349
(404 Not Found) loading http:…pp.module" from
http://localhost:3000/src/main.js", originalErr:
ZoneAwareError}
Any help would be much appreciated, I can't get past this.
It is not liking something about the reference in this line and getting lost somewhere in zone.js, but I can't get it right. I am using the starter kit from angular.io and using their file layout.
System.import('src/main.js').catch(function(err){ console.error(err); });
I was able to fix by adding two more static routes to the express server so it looked in every folder.
app.use(express.static(path.join(__dirname, 'client'))); // folder where angular will be installed
app.use(express.static(path.join(__dirname, 'client', 'src')));
app.use(express.static(path.join(__dirname, 'client', 'src', 'app')));
This fixed the issue.
I have encountered the same problem with the new version of Quickstart. The fact that it has a different structure (src folder added) affects how express will behave. In my scenario I have NOT altered this portion.
System.import('src/main.js').catch(function(err){ console.error(err); });
Instead I left it as default (I believe angular handles where to look for it).
System.import('main.js').catch(function(err){ console.error(err); });
I have added one more static route. Make sure you have both, one of them will not suffice.
app.use(express.static(path.join(__dirname, 'client')));
app.use(express.static(path.join(__dirname, 'client/src')));
if you are following the TRAVERSY MEDIA: (original Source is EDUONIX)
https://www.youtube.com/watch?v=PFP0oXNNveg&t=2304s
after creating the 'client' folder. Skip the whole JSON Part.
Open Terminal
git clone https://www.github.com/angular/quickstart client
npm install
npm start (this will give you the complete start of the angular front-end)
ctrl + C (close the webserver)
npm run build
server.js
var express = require ('express');
var path = require ('path');
var bodyParser = require ('body-parser');
var index = require ('./routes/index');
var todos = require ('./routes/todos');
var app = express();
//View Engine
app.use(express.static( path.join(__dirname, 'client') ) );
app.use(express.static( path.join(__dirname, 'client/src')));
app.use(express.static( path.join(__dirname, 'client/bower_components')));
app.set('views', path.join(__dirname, 'client/src') );
app.set('view engine', 'ejs');
app.engine ('html', require('ejs').renderFile );
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false} ));
app.use('/', index);
app.use('/api/v1', todos);
app.listen(3000, function() {
console.log ('server started on port 3000');
/routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index.html');
});
module.exports = router;
Last but not the least:
make sure this route would execute:
http://localhost:3000/api/v1/todos
yes? (you did it)
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
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');
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).
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.